需要添加类名 top
代码语言:javascript复制// 平滑滚动到顶部
var scrollTopSmooth = function (position) {
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (cb) {
return setTimeout(cb, 10);
};
}
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var step = function () {
var distance = position - scrollTop;
scrollTop = scrollTop distance / 5;
if (Math.abs(distance) < 1) {
window.scrollTo(0, position);
} else {
window.scrollTo(0, scrollTop);
requestAnimationFrame(step);
}
};
step();
}
$backToTop = document.querySelector('.top')
$backToTop.addEventListener('click', function () {
scrollTopSmooth(0);
}, false);
更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/120074347