需求:需要滾動條緩慢移動到某個位置
scrollAnimation(currentY, targetY) {
// 擷取目前位置方法
// 計算需要移動的距離
let needScrollTop = targetY - currentY
let _currentY = currentY
setTimeout(() => {
// 一次調用滑動幀數,每次調用會不一樣
const dist = Math.ceil(needScrollTop / 10)
_currentY += dist
window.scrollTo(_currentY, currentY)
// 如果移動幅度小于十個像素,直接移動,否則遞歸調用,實作動畫效果
if (needScrollTop > 10 || needScrollTop < -10) {
this.scrollAnimation(_currentY, targetY)
} else {
window.scrollTo(_currentY, targetY)
}
}, 1)
執行的地方:
比如移動到頂部
const currentY = document.documentElement.scrollTop || document.body.scrollTop
this.scrollAnimation(currentY, 0)
比如移動到底部(頁面容器id為page)
const currentY = document.documentElement.scrollTop || document.body.scrollTop
const bottomY = document.getElementById("page").clientHeight
this.scrollAnimation(currentY, bottomY )