JS返回顶部实例代码
网络 2017-11-01 2892
本文实例为大家分享了JS返回顶部实例代码,供大家参考,具体内容如下
html/css部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <!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="/535e0ce800015b7511902787.jpg" alt=""> <a id="btn" href="javascript:" class="btn" title="回到顶部"></a> </div> </body> </html> |
JS部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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); } } |
下一篇:js实现Tab选项卡切换效果