The example in this article introduces the implementation method of the JavaScript return to the top button, and shares it with everyone for your reference. The specific content is as follows
html:
<a href="javascript:;" id="btn" title="回到顶部"></a>
css:
#btn{position:fixed;display:none;}
script:
Get the scroll bar height:document.documentElement.scrollTop || document.body.scrollTop
Get the height of the visual area:document.documentElement.clientHeight
js code
window.onload = function(){ var obtn = document.getElementById('btn'); //获取页面可视区的高度 var clientHeight = document.documentElement.clientHeight; var timer = null; var isTop = true; window.onscroll = function(){ var osTop = document.documentElement.scrollTop || document.body.scrollTop; if (osTop >= clientHeight){ //显示按钮 obtn.style.display = 'block'; }else { //隐藏按钮 obtn.style.display = 'none'; } if (!isTop){ clearInterval(timer); } isTop = false; }; obtn.onclick = function(){ //设置定时器 timer = setInterval(function(){ //获取滚动条距离顶部的高度 var osTop = document.documentElement.scrollTop || document.body.scrollTop; var ispeed = Math.floor(-osTop / 6); document.documentElement.scrollTop = document.body.scrollTop = osTop +ispeed; isTop = true; if (osTop === 0){ clearInterval(timer); } },30); }; };
I hope this article will be helpful to everyone learning JavaScript programming.