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

标签 javascript jquery

如何跟踪滚动到哪个 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 {

    }
});

关于javascript - 如何跟踪滚动到哪个 div 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22492796/

相关文章:

javascript - React.js 测试未能找到组件

php - 在表单上提交发送电子邮件+打开弹出窗口

jQuery 文件上传 : post only file input field

javascript - 使用 ".remove()"函数时代码未运行

javascript - 使用 Knockout.js 和 Ajax 上传附件

javascript - 为什么不应用 material-ui 的 darkBaseTheme?

javascript - .getAttribute 不是函数

javascript - 不要将 br 和 nbsp 计入字符串中

javascript - 在已经在顶部时检测滚动事件

javascript - 文本链接填写表单字段