原生js回到顶部

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.test{
background: #ff0000;
width:100%;
height: 5000px;;
}
.top{
width:50px;
height:50px;
position: fixed;
right:20px;
bottom:20px;
background: #424242;
line-height: 50px;
text-align: center;
cursor: pointer;
}
</style>
</head>
<body>
<div class="test">
<div class="top">click me</div>
</div>
<script type="text/javascript">
var clickBtn=document.getElementsByClassName("top")[0];
var timer=null;
clickBtn.addEventListener("click",function () {
timer=setInterval(function(){
scrollTopm=document.body.scrollTop;
if(scrollTopm<=0){clearTimeout(timer);}
else{
          document.documentElement.scrollTop = document.body.scrollTop =scrollTopm/3; //剩余距离的三分之一回到顶部
       } ,200});
  }
</script>
</body></html>
上一篇:Nginx 日志文件 access_log 详解


下一篇:js回到顶部