javascript - 在没有滚动的情况下到达页面底部时如何在JS中触发事件
问题描述
我有一个用于滚动到页面底部的事件监听器可以正常工作:
document.addEventListener('scroll', () => {
if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
console.log("bottom reached");
}
});
但我的问题是,如果页面加载并且文档比窗口短,则不会触发,因为没有滚动事件。换句话说,文档适合窗口,因此无需滚动到底部。
不过,在这种情况下,我仍然想触发一些东西。我怎么做?
我想过在 DOMContentLoaded 事件侦听器中有一个条件语句来检查窗口是否大于文档,即
if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
console.log("window size exceeds page size");
}
虽然这可行,但它在控制台中给了我一个“强制回流”性能违规警告,基本上说这花费了太长时间。
关于如何处理这个问题的任何建议?
解决方案
您的解决方案是最简单的,如果您没有任何其他问题而不是控制台中的警告,它可能是最好的。
另一种方法是使用在加载时执行的Intersection Observer API 。
这是一个简单的例子:
<head>
<style>
.container {
width: 100%;
height: 80%;
background-color: whitesmoke;
}
</style>
</head>
<body>
<div class="container"></div>
<script>
const container = document.querySelector('.container')
const observer = new IntersectionObserver(callback, {
root: null, // intersect with viewport
rootMargin: '0px', // no margin when computing intersections
threshold: 1.0, // execute callback when every pixel is visible
})
function callback(entries) {
for (const entry of entries) {
if (entry.isIntersecting) {
console.log("i am also fired on load")
}
}
}
observer.observe(container)
</script>
</body>
您还可以观察页面底部的页脚或某些元素。使用 Intersection Observer,您甚至不必使用scroll
事件侦听器。
推荐阅读
- angular - 在引导期间首次加载 Angular 应用程序时,组件模板中的图片是否会加载到客户端浏览器?
- openebs - 无法正确删除 cStor 卷副本
- python - 仅使用 python 在子目录中查找文件
- excel - VBA:根据第二列中的出现次数查找一列中的出现次数
- karate - 如何使用从 karate-config.js 到 .feature 文件的变量
- apache-camel - 如何在 apache camel 中发送空响应以进行休息呼叫
- ssl - 连接到生产者时出错:错误:ssl.certificate.location 失败
- opencv - opencv:显示图像并等待变量更改,而不是等待按键
- db2 - 如何更改 SYSIBMADM.PRIVILEGES 表中的 GRANTABLE?
- python - 在烧瓶中使用 SQL alchemy 将数据插入 Postgres