代码实现:【返回顶部】默认隐藏,当windowY滚轴往下滑动至一定距离才显示【返回顶部】
主要思路:点击监听事件 & 滚轴事件 & 周期定时器
js代码:
<script>
// 返回按钮默认隐藏
let btn = document.querySelector("button");
// 定时器周期获取Y滚轴的位置
// 判定当Y滚轴往下滚动超过设定位置就显示按钮
btn.addEventListener("click", function () {
let location = scrollY;
let time = setInterval(function () {
location -= 20;
scrollTo(0, location); // 按钮返回函数
if (location < 0) {
clearInterval(time); //结束滚轴跳转后,滚轴位置归零
scrollY(0, 0)
}
// 添加滚轴事件,判定在返回过程中,滚轴y位置发生变化,即终止定时器
window.addEventListener("scroll", function () {
if (scrollY != local) {
clearInterval(time);
}
})
}, 10);
})
// 方法一:利用定时器判定
// let a = setInterval(function () {
// if (scrollY > 400) {
// btn.style.display = "inline";
// }else{
// btn.style.display="none";
// }
// }, 10)
// 方法二:利用滚轴监听事件
window.addEventListener("scroll", function () {
if (scrollY > 400) {
btn.style.display = "inline";
}
else {
btn.style.display = "none";
}
})
</script>
css代码:
<style>
button {
width: 80px;
height: 80px;
background: turquoise;
border: none;
border-radius: 20px;
color: tomato;
text-align: center;
/* line-height: 80px; */
font-size: 24px;
position: fixed;
bottom: 25px;
right: 25px;
display: none;
}
div {
font-size: 26px;
/* background: royalblue; */
text-align: center;
}
</style>
html代码:
<body>
<div>
网页顶部
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div>
网页中间
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div>
网页底部
</div>
<button>返回顶部</button>
</body>