const ScrollTop = (number = 0, time) => {
if (!time) {
document.body.scrollTop = document.documentElement.scrollTop = number;
return number;
}
const spacingTime = 20; // 設置循環的間隔時間 值越小消耗性能越高
let spacingInex = time / spacingTime; // 計算循環的次數
let nowTop = document.body.scrollTop + document.documentElement.scrollTop; // 獲取當前滾動條位置
let everTop = (number - nowTop) / spacingInex; // 計算每次滑動的距離
let scrollTimer = setInterval(() => {
if (spacingInex > 0) {
spacingInex--;
ScrollTop(nowTop += everTop);
} else {
clearInterval(scrollTimer); // 清除計時器
}
}, spacingTime);
};
// 滾動到距離頁面頂部500px的位置 動畫時間爲200ms
ScrollTop(500, 200);複製代碼