(踩坑)JS监听页面滚动事件无效

1,318 阅读1分钟

1.需求背景

在项目中,PC端和移动端是同一套代码,PC端用分页,移动端用滚动分页,加载更多

2.遇到问题

在PC浏览器运行时能够正常监听"scroll"事件,但是在移动端浏览器运行时window.addEventListener(“scroll”, function(){});监听无效,滚动事件无法触发。

3.window.addEventListener(“scroll”, function(){});监听无效解决方案

window.addEventListener("scroll",function(){},true);

给addEventListener加上第三个参数true,使其在事件捕获的时候触发,该值默认为false

扩展: addEventListener()基本上有三个参数,

  • 「事件名称」
  • 「事件的处理程序」(事件触发时执行的function)
  • 「Boolean」值,由这个Boolean决定事件是以「捕获」还是「冒泡」机制执行,若不指定则预设为「冒泡」。

4.const scrollTop = document.documentElement.scrollTop;scrollTop始终为0

获取不到scrollTop,scrollTop始终为0,需做兼容性处理:

const scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

5.代码示例

function debounce(method, delay) {
    let timer = null;
    return function () {
        let self = this, args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            method.apply(self, args);
        }, delay);
    }
}

if(!isPc){
    window.addEventListener('scroll', debounce(function () {
        // 获取滚动容器的高度
        const containerHeight = window.innerHeight;
        // 获取滚动内容的实际高度
        const contentHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
        // 获取当前滚动的位置
        const scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        // 判断是否滑动到了底部
        if (scrollTop + containerHeight >= contentHeight) {
        // 在滑动到底部时执行的操作
            if(currentPage<pagecount){
                currentPage++;  
                currentViewModel.searchRegulations(currentPage)
            }
        }
    }, 250),true)

}