<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>回到顶部</title>
<style>
* { padding: 0; margin: 0; }
#box {width: 100%;height: 2400px;margin: auto;border: 1px solid red;box-sizing: border-box;}
#top {width: 60px;height: 50px;line-height: 50px;background-color: orange;color: #fff;font-size: 12px;text-align: center;position: fixed;
right: 20px;bottom: 20px;text-decoration: none;display: none;
}
</style>
</head>
<body>
<div id="box"></div>
<a href="javascript:;" id="top">返回顶部</a>
</body>
<script>
window.onload = function () {
var oTop = document.getElementById('top')
// 获取页面可视区的高度
var clientHeight = document.documentElement.clientHeight
var timer = null
var isTop = true
// 滚动条滚动时触发
window.onscroll = function () {
var osTop = document.documentElement.scrollTop || document.body.scrollTop
if (osTop >= clientHeight) {
oTop.style.display = 'block'
} else {
oTop.style.display = 'none'
}
if (!isTop) {
clearInterval(timer)
}
isTop = false
}
oTop.onclick = function () {
timer = setInterval(function () {
// 获取滚动条距离顶部的高度
var osTop = document.documentElement.scrollTop || document.body.scrollTop
var ispeed = Math.floor(-osTop / 5)
document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed
isTop = true
if (osTop === 0) {
clearInterval(timer)
}
}, 30)
}
}
</script>
</html>