回到顶部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{margin:0;padding:0;}
body{
position:relative;
}
body p{
position:absolute;
bottom:0;
left:100px;
font-size: 20px;
}
#go_up{
position:fixed;
bottom:0;
right:0;
width: 100px;
height: 100px;
background:#ccc;
line-height: 100px;
text-align: center;
cursor:pointer;
display:none;
}
</style>
</head>
<body style="height:2500px;">
<p>有志者事竟成,礼拜放假星期天</p>
<div id="go_up">返回顶部</div>
</body>
<script>
var goBtn=document.getElementById('go_up');
window.onscroll=function(){
//获取当前滚动的距离(兼容写法)
var nowTop=document.body.scrollTop||document.documentElement.scrollTop;
// if(nowTop>0){
// goBtn.style.display="block";
// }else{
// goBtn.style.display="none";
// }
//三目运法(如果获取的滚动高度>600;那么就让div显示,否则,隐藏)
goBtn.style.display=nowTop>600?"block":"none";
}
//点击事件,回到顶部
goBtn.onclick=function(){
document.body.scrollTop=0;
document.documentElement.scrollTop=0;
}
</script>
</html>
![Upload Paste_Image.png failed. Please try again.]