一般返回顶部有两种方法,一种是锚链接
直接链接到顶部
href = "#"
另外一种是js
html中
<a href="javascript:;" id="btn" title="回到顶部">回到顶部</a>
js代码
window.onload = function () {
var obtn = document.getElementById('btn');
var timer = null;
var isTop = true;
window.onsroll = function () {
if (!isTop) {
clearInterval(timer);
};
isTop = false;
}
obtn.onclick = function () {
timer = setInterval(function () {
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
document.documentElement.scrollTop = document.body.scrollTop = osTop + speed;
isTop = true;
var speed = Math.floor(-osTop/5);
if (osTop == 0) {
clearInterval(timer);
};
}, 30);
}
}