javascript返回顶部的按钮实现方法

<a href="javascript:;" title="回到顶部"></a>

css:

#btn{position:fixed;display:none;}

script:

获取滚动条高度:document.documentElement.scrollTop || document.body.scrollTop

获取可视区高度:document.documentElement.clientHeight
js代码

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); }; };

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwjjs.html