实现回到顶部效果
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>返回顶部</title>
<style type="text/css">
body { margin: 0; padding: 0; height: 5000px; }
#back {
display: none;
position: fixed;
right: 10px;
bottom: 10px;
width: 40px;
height: 40px;
background-color: pink;
text-align: center;
font-size: 14px;
cursor: default;
}
p {
position: absolute;
left: 0;
right: 0;
bottom: 0;
background-color: skyblue;
}
</style>
</head>
<body>
<div id="back">返回顶部</div>
<p>lm</p>
<script type="text/javascript">
const oDiv = document.getElementById('back')
const body = document.querySelector('body')
function getView(attr){
return document.documentElement[attr] || document.body[attr]
}
//获取当前页面可视高度
let ch = getView('clientHeight')
//监听滚轮滚动事件
body.onscroll = function () {
let st = getView('scrollTop')
//滚轮滚下一半出现回到顶部按钮 个人认为体验效果更好@_@
if (st >= 0.5 * ch) {
oDiv.style.display = 'block'
} else {
oDiv.style.display = 'none'
}
}
oDiv.onclick = toTop
function toTop() {
//开局一个清除定时器
clearTimeout(this.timer)
oDiv.timer = null
//每次减少250px
document.documentElement.scrollTop -= 250
//添加一种突然加速的效果
if (document.documentElement.scrollTop <= 500) {
document.documentElement.scrollTop = 0
return
}
// toTop() 直接调用回得太快了 所以舍弃
oDiv.timer = setTimeout(toTop, 50)
}
</script>
</body>
</html>