首页 > 解决方案 > 在没有滚动的情况下到达页面底部时如何在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");
}

虽然这可行,但它在控制台中给了我一个“强制回流”性能违规警告,基本上说这花费了太长时间。

关于如何处理这个问题的任何建议?

标签: javascript

解决方案


您的解决方案是最简单的,如果您没有任何其他问题而不是控制台中的警告,它可能是最好的。

另一种方法是使用在加载时执行的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事件侦听器。


推荐阅读