我用這個javascript來檢測幾個文本框何時到達屏幕頂部。當這種情況發生時,它們應該保持固定在頂部,而其余的風箱應該在滾動時上升到前面的風箱之上。
當。固定類沒有定義,但是當我定義的時候。當第一個文本框到達窗口頂部時,所有stickyBoxes的stickyBoxOffset等于window.scrollY(你可以在下面的console.log截圖中看到)。我想這是因為“粘性應用”這個位置把一切都搞砸了,但我找不到任何其他有效的方法。我還嘗試了getBoundingClientRect(),得到了相同的結果。
有人知道到底發生了什么以及如何解決嗎?非常感謝!
// STICKY EFFECT FOR SERVICES
window.addEventListener('scroll', function() {
var stickyBoxes = $('.service-text-box')
for (var i = 0; i < stickyBoxes.length; i++) {
var stickyBoxOffset = stickyBoxes.eq(i).offset().top
// var rect = stickyBox.getBoundingClientRect()
// var offsetTop = stickyBox.offset()
console.log("------")
console.log(stickyBoxes.eq(i).attr('id'))
console.log(stickyBoxOffset)
console.log(window.scrollY)
// console.log(offsetTop)
console.log("------")
if (stickyBoxOffset <= window.scrollY) {
stickyBoxes.eq(i).addClass('fixed');
}
else {
stickyBoxes.eq(i).removeClass('fixed');
}
}
});
.services .service-left, .services .service-right { position: relative; }
.services .service-left .service-text-box { padding: 130px 115px; z-index: 2; }
.services .service-text-box.fixed { position: fixed!important; top: 0; width: 50%; height: auto; }
.greenBox { background-color: #01C4B8; color: white; height:200px }
.yellowBox { background-color: #FFC43D; color: white; height:200px }
.blueBox { background-color: #084559; color: white; height:200px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12 col-lg-6 service-left p-0">
<div class="greenBox service-text-box" id="service-text-box-1">
<div class="service-title">asdfasdf</div>
<div class="service-detail">
asdfasdf
</div>
</div>
<div class="yellowBox service-text-box" id="service-text-box-2">
<div class="service-title">asdfasdf</div>
<div class="service-detail">
<p>asdfasdf</p>
<p>asdfasdf</p>
</div>
</div>
<div class="greenBox service-text-box" id="service-text-box-3">
<div class="service-title">asdfasdf</div>
<div class="service-detail">
<p>asdfasdf</p>
<p>asdfasdf</p>
</div>
</div>
<div class="blueBox service-text-box" id="service-text-box-4">
<div class="service-title">asdfasdf</div>
<div class="service-detail">
<p>asdfasdf</p>
<p>asdfasdf</p>
</div>
</div>
<div class="greenBox service-text-box" id="service-text-box-5">
<div class="service-title">asdfasdf</div>
<div class="service-detail">
<p>asdfasdf</p>
<p>asdfasdf</p>
</div>
</div>
<div class="blueBox service-text-box" id="service-text-box-6">
<div class="service-title">asdfasdf</div>
<div class="service-detail">
<p>asdfasdf</p>
<p>asdfasdf</p>
</div>
</div>
</div>