解决滚动条滚动事件(window.onscroll)产生的窗口抖动问题

it2023-06-27  102

在使用window.onscroll(滚动条滚动事件)时,会产生窗口抖动的情况

解决方法:

可通过setTimeout()方法设置一个延时器,设定一定毫秒后,再执行滚动条滚动事件触发时应该执行的代码。这样一定程度上的避免了窗口抖动。

代码:

/** *滚动条滑倒底部打印日志:没有更多 */ var timeOut = null; window.onscroll = function () { // 防止窗口抖动 if (timeOut) { clearTimeout(timeOut); } timeOut = setTimeout(function () { //变量scrollTop是滚动条滚动时,距离顶部的距离 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //变量windowHeight是可视区的高度 var windowHeight = document.documentElement.clientHeight || document.body.clientHeight; //变量scrollHeight是滚动条的总高度 var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight; //滚动条到底部的条件 if (scrollTop + windowHeight == scrollHeight) { console.log("已经滑到底啦"); } else { console.log("还有数据可以浏览哦"); } }, 500); }

 

最新回复(0)