JavaScript监听滚动条停止滚动

需求:当滚动条滚动时将x元素隐藏掉,当滚动条停止滚动时再将元素x显示出来。

let scrollTop = 0;
let scrollEndTop = 0;
let timer = null;

document.onscroll = function() {
  clearTimeout(timer);
  timer = setTimeout(isScrollEnd, 500);
  scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
}

function isScrollEnd() {
    scrollEndTop = document.documentElement.scrollTop || document.body.scrollTop;
    if(scrollTop === scrollEndTop){
        console.log('滚动条停止滚动');
    }
}

tips:在控制元素x显隐时,我使用的是v-show,没有使用v-if,一方面元素x经常显隐切换影响性能;另一方面,如果使用v-if,会是元素x重新执行生命周期钩子,会导致元素x的element_show埋点误报(重复上报)。