html
代码
<div>
<a class = "back" />
<p>回到顶部</p>
...
<p>回到顶部</p>
</div>
js
代码
<script>
let back = document.querySelector('.back')
let dis
window.onscroll = function() {
dis = document.documentElement.scrollTop || document.body.scrollTop
if(dis >= 500) {
back.style.opacity = '1'
} else {
back.style.opacity = '0'
}
}
let timer = null
back.onclick = function() {
// 防止连续几次点击
clearInterval(timer)
if(dis > 0) {
timer = setInterval(function() {
var speed = (0 - dis)/7
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
dis += speed
document.documentElement.scrollTop = dis
if(dis <= 0) {
clearInterval(timer)
}
}, 30)
}
}
</script>