Home >Web Front-end >JS Tutorial >JS return to top example sharing
This article mainly introduces the JS return to the top example code in detail, which has certain reference value. Interested friends can refer to it. I hope it can help everyone.
The example in this article shares the JS return to the top example code for your reference. The specific content is as follows
html/css part
<!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> <p class="container"> <img src="/535e0ce800015b7511902787.jpg" alt=""> <a id="btn" href="javascript:" class="btn" title="回到顶部"></a> </p> </body> </html>
JS part
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); } }
Related recommendations:
Several common web pages return to the top code
JavaScript simple return to top code and comment description
Use JQUERY to achieve variable transparency return to top effect
The above is the detailed content of JS return to top example sharing. For more information, please follow other related articles on the PHP Chinese website!