滚动到距离到400px的时候对盒子进行隐藏
当滚动条滚动400px的时候对盒子进行隐藏:
点击盒子返回到顶部
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.content {
height: 2000px;
}
.goTop {
width: 100px;
height: 100px;
background-color: #bbb;
text-align: center;
line-height: 100px;
bottom: 100px;
right: 20px;
/* display: none; */
margin-top: 500px;
}
</style>
</head>
<body>
<div class="content">
<h2>返回首屏</h2>
<div class="goTop" id="goTop">返回</div>
</div>
</body>
<script>
// 当用户滑动滚动条到达400px 返回按显示 ,反之小于400时隐藏
let goTop = document.getElementById("goTop");
window.onscroll = function () {
let res = document.body.scrollTop || document.documentElement.scrollTop;
console.log(res);
if (res >= 400) {
goTop.style.display = "block";
} else {
goTop.style.display = "none";
}
};
// 当用户点击的时候
goTop.onclick = function () {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
};
</script>
</html>
事件处理的重点:
1.为了进行更好的兼容
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
2. window.onscroll 监听窗口的滚动