来实现一个js平滑滚动到顶部的小功能
作者:互联网
需要添加类名 top
// 平滑滚动到顶部
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
标签:function,distance,滚动,平滑,js,window,var,scrollTop,document 来源: https://www.cnblogs.com/wangchuanxinshi/p/16507948.html