javascript - 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>
解决方案
啊,我刚想通了。由于 null 元素,我的 percentInViewport 函数有问题。正如有人建议的那样,从控制台进行了一些调试并且滚动工作哈哈。谢谢!
推荐阅读
- python - Cloudera 烧瓶应用程序
- android - 严格的安全 Cookie 政策不允许为 http://googleads.g.doubleclick.net/ 设置安全 Cookie
- sql - SQL中只查询满足三个条件的一行
- embedded-linux - 无法向 Yocto 映像添加简单的内核模块
- javascript - 在表单中动态生成嵌套输入
- java - 使用 facebook Graph API 使用短代码获取 instagram 视频指标
- posix - 可以将使用 boost 库在传统软件堆栈中编写的应用程序移植到自适应 AUTOSAR 堆栈中吗
- multithreading - Express js 多线程
- c# - 提取文件头签名,因为它在 ASP.NET Core 中直接流式传输到磁盘
- javascript - 使用“Date.prototype.toISOString”时可以去掉“.000Z”吗?