首页 > 解决方案 > Document.scroll 不适用于多个 html 页面

问题描述

我有多个 html 页面(页面 A 和页面 B),当用户在任一页面上滚动时,我需要检测每个页面上的某些 div 是否在视图中。两个页面相互链接并共享相同的 js 脚本。现在的问题是,当我滚动并导航到另一个页面时,它只检测到 pageA 的 div 而不是 pageB。当我注释掉pageA(checkPageA())的函数时,它适用于pageB。我不确定发生了什么以及为什么它不适用于两个页面。

我不确定如何在此处显示多个 html 页面,因此这是我的代码的简化版本(由于页面未在此处连接,因此无法运行)。我想将两个页面保留为单独的 HTML 文件,而不是将它们组合在一起。谢谢!

$(document).ready(function() {

  $(document).scroll(function() {
    checkPageA();
    checkPageB();
  });

  function checkPageA() {
    if (percentInViewport(".pageA", 10)) {
      alert("pageA");
    }
  }


  function checkPageB() {
    if (percentInViewport(".pageB", 10)) {
      alert("pageB");
    }
  }

  /**Checks if div is in the viewport by percentVisible**/
  function percentInViewport(objectString, percentVisible) {
    var el = document.querySelector(objectString);
    rect = el.getBoundingClientRect();
    windowHeight = (window.innerHeight || document.documentElement.clientHeight);
    return !(
      Math.floor(100 - (((rect.top >= 0 ? 0 : rect.top) / + -(rect.height / 1)) * 100)) < percentVisible ||
      Math.floor(100 - ((rect.bottom - windowHeight) / rect.height) * 100) < percentVisible
    )
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- HTML for Page A-->
<html>

<body>
  <a href="pageB.html">Go to Page B</a>
  <div class="pageA">This is page A</div>
</body>

</html>

<!-- HTML for Page B-->
<html>

<body>
  <a href="pageA.html">Go to Page A</a>
  <div class="pageB">This is page B</div>
</body>

</html>

标签: javascripthtmljquery

解决方案


啊,我刚想通了。由于 null 元素,我的 percentInViewport 函数有问题。正如有人建议的那样,从控制台进行了一些调试并且滚动工作哈哈。谢谢!


推荐阅读