繁体   English   中英

如何跟踪滚动到哪个div位置?

[英]How to track scroll to which div position?

如何跟踪滚动到哪个div位置? 当div高度不固定且不确定(从db select中)时,如何滚动到每个div然后做些什么...

我应该将每个div位置存储到数组中,然后如果在数组中滚动位置,则滚动到键div? 但这似乎会崩溃.....

<div class="1">1</div> // 10px height
<div class="2">2</div> // 13px height
<div class="3">3</div> // 11px height
… // … height 

加载DOM时,所有元素都有一个偏移量。

如果要将所有顶部推入阵列,请执行以下操作。 然后,在滚动时,将窗口滚动位置与数组进行比较。 如果它与数组编号匹配,请对该数组编号执行所需操作。 这是未经测试的代码,但是理论在那里

var divTops = [];  //Start an empty array
$(document).ready(function(){  //When the DOM loads
    $('div').each(function(e){ //For each div
        var top = $(this).offset().top; //Get its top
        divTops.push(top);  //and push that top into the array
    });
});

$(window).scroll(function(){  //When the user scrolls
    var scrolled = divTops.indexOf($(window).scrollTop());  //get the index number 
    if(scrolled === 0){  // Use the index number to control whatever is there.
        //Do something with the first div
    } else if(scrolled === 1){
        //Do something with the second div
    } else if(scrolled === 2){
        //Do something with the third div
    } else {

    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM