Home  >  Article  >  Web Front-end  >  Javascript return to top button implementation method_javascript skills

Javascript return to top button implementation method_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:20:551531browse

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn