<style>
*{
margin:0;
padding: 0;
}
.content{
height: 2000px;
}
.goTop{
width: 100px;
height: 100px;
background-color: #bbb;
text-align: center;
line-height: 100px;
position:fixed;
bottom:100px;
right: 20px;
display: none;
}
</style>
<div class="content">
<h2>返回首屏</h2>
<div class="goTop">返回</div>
</div>
<script>
// 逻辑:1.当用户滑动滚动条 到达400px,返回按钮显示,反之小于400时 隐藏
// 2.点击 返回按钮 时 滚动条恢复原位
// 让谁进行滚动 body html
let goTop = document.getElementsByClassName('goTop')[0];
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>