在utils文件内封装scrollSmoothTo.js文件
export default function scrollSmoothTo(position) {
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (callback, element) {
return setTimeout(callback, 17);
};
}
let scrollTop =
document.documentElement.scrollTop || document.body.scrollTop;
let 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();
}
使用
import scrollSmoothTo from "@/utils/scrollSmoothTo";
scrollSmoothTo(0);