需求:点击按钮后可以由快到慢的返回顶部,处于顶部位置时按钮消失
样式:
<style>
.bigbox {
width: 200px;
height: 20000px;
background-color: gold;
float: left;
}
.anniu {
position: fixed;
bottom: 150px;
right: 50px;
display: none;
width: 100px;
height: 100px;
background-color: red;
color: white;
text-align: center;
line-height: 100px;
}
p{width: 100%;height: 300px;background-color: aqua;text-align: center;line-height: 300px;color: black;}
</style>
<body>
<p>这是顶部</p>
<div class="bigbox">
</div>
<div class="anniu">返回顶部</div>
JS代码:
<script>
var height
var anniu = document.querySelector('.anniu')
window.onscroll = function () {
xianshi()
}
function xianshi() {
var height = document.documentElement.scrollTop;
if (height > 0) {
anniu.style.display = 'block'
} else {
anniu.style.display = 'none'
}
}
anniu.onclick = function () {
let scrollTop = document.documentElement.scrollTop
let timer = setInterval(function () {
scrollTop = scrollTop / 2
if (scrollTop <= 300) {
clearInterval(timer)
document.documentElement.scrollTop = 0
}
else { document.documentElement.scrollTop = scrollTop}
}, 200)
}
</script>
原理:
顶部按钮位置消失原理:
1.查询元素以便进行样式修改
2.onscroll函数判定是否有滚轮的滚动,每一次滚动执行一次判定函数
3.如果距离顶部的距离大于0的话就会显示为块,小于0 的话就会显示为none
由快到慢往上原理:
1。让滚动条每次往上滚动的距离为距离顶部的二分之一
2.通过定时器没两百毫秒执行一次向上的函数,如果到达顶部了就取消定时器