滾動可以分為窗口滾動和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的優(yōu)勢主要有兩點:
1锐秦、requestAnimationFrame 會把每一幀中的所有DOM操作集中起來华嘹,在一次重繪或回流中就完成,并且重繪或回流的時間間隔緊緊跟隨瀏覽器的刷新頻率稳衬,一般來說瘟忱,這個頻率為每秒60幀。
2手销、在隱藏或不可見的元素中歇僧,requestAnimationFrame將不會進行重繪或回流,這當然就意味著更少的的cpu锋拖,gpu和內存使用量诈悍。