首页 > 解决方案 > 在 jQuery 中使用随机数的 div 动态检测页面滚动上的当前 div

问题描述

我有一个包含多个 a4 页面(数字是随机的)的容器,我想检测我当前正在查看的页面。

这是我的代码:

<div class="mycont">

    <div id="page1" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
        <h1>page1</h1>
    </div>

    <div id="page2" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
        <h1>page2</h1>
    </div>

    <div id="page3" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
        <h1>page3</h1>
    </div>

</div>

<div style="position: fixed; bottom: 0; left: 50%; padding: 10px 50px; background-color: #ccc;" id="curpage">cur page 1</div>

有了这个脚本,我只能检测到 1 页

<script>
$(document).ready(function() {
  var target = $("#page2").offset().top;
  var interval = setInterval(function() {
    if ($(window).scrollTop() >= target) {
      $("#curpage").text("cur page 2");
    }
  }, 250);
});
</script>

如何检测页面 3,4... 50,51 等?

标签: jquery

解决方案


您可以使用Intersection Observer

let observer = new IntersectionObserver(function(entries) {
    var ele = entries.filter(entry => entry.isIntersecting);
    if (ele.length > 0) {
        ele = ele[0].target;
        console.log('Visible element is now: ' + ele.id);
    }
});

document.querySelectorAll('.mycont [id^=page]')
                             .forEach(ele => observer.observe(ele));
<div class="mycont">

    <div id="page1" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
        <h1>page1</h1>
    </div>

    <div id="page2" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
        <h1>page2</h1>
    </div>

    <div id="page3" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
        <h1>page3</h1>
    </div>

</div>

<div style="position: fixed; bottom: 0; left: 50%; padding: 10px 50px; background-color: #ccc;" id="curpage">cur page 1</div>


推荐阅读