背景:在项目里需要用到回到顶部,于是总结了一下,封装成一个js,以牛奶般顺滑的用户体验为目的,如下:
js实体:
export function scrollTopSmooth(position = 0) {
// 不存在原生`requestAnimationFrame`,用`setTimeout`模拟替代
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (cb) {
return setTimeout(cb, 17)
}
}
// 当前滚动高度
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const step = function () {
let distance = position - scrollTop
scrollTop = scrollTop + distance / 5
if (Math.abs(distance) < 1) {
window.scrollTo(0, position)
} else {
window.scrollTo(0, scrollTop)
requestAnimationFrame(step)
}
}
step()
}
用法:
scrollTopSmooth(0)