原生js实现滑动并监听滑动事件

2022-03-23  本文已影响0人  B612的末影人

滚动可以分为窗口滚动div滚动

窗口滚动

因为要兼容不同浏览器,窗口滚动的当前高度是取这三个值

document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop

div滚动

假设html代码如下:

<div class="scroll-view">
    <div class="content" >
        <p>...</p>
        <p>...</p>
        ...
    </div>
</div>

<style>
    .scroll-view {
        height: 100%;
        overflow-x: hidden;
        overflow-y: scroll;
    }
</style>

这么取当前位置:

const $ = document.querySelector.bind(document)
function doSomething (currentY) {
    console.log('当前位置', currentY);
}
let lastKnownScrollPosition = 0;
let ticking = false;
$('.scroll-view').addEventListener('scroll', function(e) {
    lastKnownScrollPosition = e.target.scrollTop;
    if (!ticking) {
        window.requestAnimationFrame(function() {
            doSomething(lastKnownScrollPosition);
            ticking = false;
        });
        ticking = true;
    }
});

这里的requestAnimationFrame是为了避免消耗过多的资源

requestAnimationFrame 比起 setTimeout、setInterval的优势主要有两点:
1、requestAnimationFrame 会把每一帧中的所有DOM操作集中起来,在一次重绘或回流中就完成,并且重绘或回流的时间间隔紧紧跟随浏览器的刷新频率,一般来说,这个频率为每秒60帧。
2、在隐藏或不可见的元素中,requestAnimationFrame将不会进行重绘或回流,这当然就意味着更少的的cpu,gpu和内存使用量。

上一篇 下一篇

猜你喜欢

热点阅读