js如何计算页面滚动的速度

js如何计算页面滚动的速度

阅读 4.1k
1 个回答

大概长这样?

let startTimer = null, timer = 0, speed = 0, s = 0, scrollTop = document.documentElement.scrollTop
const timeScale = 500   // 检测滚动停止的时间 ms
window.onscroll = function (e) {
    let tempScrollTop = document.documentElement.scrollTop
    s += Math.abs(scrollTop - tempScrollTop)
    scrollTop = tempScrollTop
    clearTimeout(startTimer)
    if (!timer) {
        timer = new Date().getTime()
    }
    startTimer = setTimeout(function () {
        let nowTimer = new Date().getTime()
        let diffTimer = (nowTimer - timer - timeScale) / 1000
        speed = s / diffTimer
        s = 0
        timer = 0
        console.log(speed)  // 所求速度 px/s
    }, timeScale)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题