点击使滚动条回到顶部

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<style type="text/css">
#box{
width: 50px;
height: 50px;
background-color: red;
position: fixed;
bottom: 10px;
right: 10px;
font-size: 30px;
color: #fff;
text-align: center;
line-height: 50px;
cursor: pointer;
display: none;
}
</style>
</head>
<body style="height: 2000px;">
<div id="box">↑</div>
</body>
</html>

<script type="text/javascript">
function goTop(element){
var element=document.getElementById(element);
window.onscroll=computedDisplay;
function computedDisplay(){
var curTop=document.documentElement.scrollTop||document.body.scrollTop;
var curHeight=document.documentElement.clientHeight||document.body.clientHeight;
element.style.display=curTop>curHeight?"block":"none";
}
element.onclick=function(){
this.style.display="none";
window.onscroll=null;
var duration=500;
var interval=10;
var target=document.documentElement.scrollTop||document.body.scrollTop;
var step=(target/duration)*interval;
var timer=window.setInterval(function(){
var curTop=document.documentElement.scrollTop||document.body.scrollTop;
if(curTop==0){
clearInterval(timer);
window.onscroll=computedDisplay;
return;
}
curTop-=step;
document.documentElement.scrollTop=curTop;
document.body.scrollTop=curTop;
},interval);
}
}
goTop("box");
</script>

猜你喜欢

转载自www.cnblogs.com/wxiang/p/9124872.html
今日推荐