Home > Web Front-end > JS Tutorial > body text

Javascript return to top button implementation method_javascript skills

WBOY
Release: 2016-05-16 15:20:55
Original
1548 people have browsed it

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>
Copy after login

css:

#btn{position:fixed;display:none;}
Copy after login

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);
  };
};
Copy after login

I hope this article will be helpful to everyone learning JavaScript programming.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template