搜索
您的当前位置:首页正文

JS返回顶部实例代码

2020-11-27 来源:意榕旅游网

本文实例为大家分享了JS返回顶部实例代码,供大家参考,具体内容如下

html/css部分

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <script src="返回顶部效果.js"></script>
<style>
 .container{
 width:1190px;
 margin: 0px auto;
 }
 .container a{
 display: none;
 width:40px;
 height:40px;
 background: url(/535e0dc100010e9c00400080.jpg) no-repeat;
 position: fixed;
 left:95%;
 bottom: 50px;
 }
 .container a:hover{
 background: url(/535e0dc100010e9c00400080.jpg) no-repeat;
 background-position: left -40px;
 }
</style> 
</head>
<body>
 <div class="container">
 <img src="https://www.gxlcms.com/535e0ce800015b7511902787.jpg" alt="">
 <a id="btn" href="javascript:" class="btn" title="回到顶部"></a>
 </div>
</body>
</html>

JS部分

window.onload=function(){
 var obtn=document.getElementById("btn");
 var clientHeight=document.documentElement.clientHeight||ocument.body.clientHeight;
 var isTop=true;
 var timer=null;
 window.onscroll=function(){
 var topH=document.documentElement.scrollTop||document.body.scrollTop;
 if(topH>clientHeight){
 obtn.style.display="block";
 }else{
 obtn.style.display="none";
 }
 }
 obtn.onclick=function(){
 timer=setInterval(function(){
 var topH=document.documentElement.scrollTop||document.body.scrollTop;
 var stepLength=Math.ceil(topH/5);
 document.documentElement.scrollTop=document.body.scrollTop=topH-stepLength;
 if(topH==0){
 clearInterval(timer);
 }
 },30);
 }
}

学习视频地址

Top