你的位置:首页 > Java教程

[Java教程]返回顶部的按钮设计


html:

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

css:

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

script:

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

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

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