一个简单的浏览器页面滚动防抖

    const scrollTimer =  ref(null) //滚动防抖定时器
    const currentTop =  ref(null) //实时滚动高度
    const scrollTop =  ref(0) //防抖结束后的滚动高度    

    function bindScrollEvent() {
      window.addEventListener('scroll', handleScrollStart);
    }

    function removeScrollEvent() {
      window.removeEventListener('scroll', handleScrollStart);
    }

    function handleScrollStart() {
      scrollTimer.value && clearTimeout(scrollTimer.value);
      scrollTimer.value = setTimeout(() => {
        handleScrollEnd();
      }, 200);
      currentTop.value = document.documentElement.scrollTop || document.body.scrollTop;
    }

    function handleScrollEnd() {
      scrollTop.value = document.documentElement.scrollTop || document.body.scrollTop;
      // 判断是否停止滚动的条件
      if (scrollTop.value == currentTop.value) {
        // do something
      }
    }

    
    onMounted(()=>{
      bindScrollEvent()
    })

    onBeforeUnmount(()=>{
      removeScrollEvent()
     })
posted @ 2025-03-04 09:05  huihuihero  阅读(18)  评论(0)    收藏  举报