返回顶部


function goTop(doc) {
var timer = null,
current = 0, //当前位置
target = 0, // 目标位置
gotop = document.querySelector(doc);
window.onscroll = function () {
// 获取scrollptop(兼容性写法)
var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
if (scrollTop > 0) {
gotop.style.display = "block";
} else {
gotop.style.display = "none";
}
current = scrollTop;
}
gotop.addEventListener('click', function () {
clearInterval(timer);
timer = setInterval(function () {
var step = (target - current) / 2;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
current = current + step;
window.scrollTo(0, current);
if (current === target) {
clearInterval(timer);
}
}, 30)
});
}

你可能感兴趣的:(返回顶部)