<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
body{
height: 3000px;
}
.show{
width: 100px;
height: 100px;
background-color: #A9A9A9;
text-align: center;
line-height: 100px;
position: fixed;
right: 30px;
top: 450px;
display: none;
}
</style>
<!-- 当页面往下到600像素时出现返回首屏盒子,当点击回到顶部盒子消失,回到0 -->
<script type="text/javascript">
window.onload = function(){
//获取div
var odiv = document.querySelectorAll(".show")[0];
//给window添加事件
window.onscroll = function(){
//拿到html距离顶部的位置或者body
var oHTml = document.documentElement.scrollTop || document.body.scrollTop;
if(oHTml >= 400){
odiv.style.display = "block";
}else{
odiv.style.display = "none";
}
odiv.onclick =() =>{
document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
console.log(oHTml);
}
}
}
</script>
</head>
<body>
<h1>返回首屏</h1>
<div class="show">
返回顶部
</div>
</body>
</html>