一、頁(yè)面滾到一定位置兔仰,觸發(fā)某個(gè)點(diǎn)擊事件,讓頁(yè)面回到頂部.
const currentY = document.documentElement.scrollTop || document.body.scrollTop;
this.scrollAnimation(currentY, 0)
// 頁(yè)面慢慢回到頂部執(zhí)行方法
scrollAnimation (currentY, targetY) {
// 獲取當(dāng)前位置方法
// 計(jì)算需要移動(dòng)的距離
let needScrollTop = targetY - currentY
let _currentY = currentY
setTimeout(() => {
// 一次調(diào)用滑動(dòng)幀數(shù)庄呈,每次調(diào)用會(huì)不一樣
const dist = Math.ceil(needScrollTop / 10)
_currentY += dist
window.scrollTo(_currentY, currentY)
// 如果移動(dòng)幅度小于十個(gè)像素鸯乃,直接移動(dòng),否則遞歸調(diào)用玄呛,實(shí)現(xiàn)動(dòng)畫效果
if (needScrollTop > 10 || needScrollTop < -10) {
this.scrollAnimation(_currentY, targetY)
} else {
window.scrollTo(_currentY, targetY)
}
}, 1)
},