javascript returns the button implementation method at the top

  • 2020-11-26 18:40:37
  • OfStack

This article introduces the javascript back to the top button implementation method, share for your reference, the specific content is as follows

html:


<a href="javascript:;" id="btn" title=" Back to the top "></a>

css:


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

script:

Gets the height of the scroll bar: document.documentElement.scrollTop || document.body.scrollTop

Gets the height of the visible area: document.documentElement.clientHeight
js code


window.onload = function(){
  var obtn = document.getElementById('btn');
  // Gets the height of the visual area of the page 
  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){
    // According to the button 
      obtn.style.display = 'block';
    }else {
    // Hide button 
      obtn.style.display = 'none';
    }
    if (!isTop){
      clearInterval(timer);
    }
    isTop = false;
  };
  obtn.onclick = function(){    
    // Set timer 
    timer = setInterval(function(){
      // Gets the height of the scroll bar from the top 
      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 has been helpful in learning javascript programming.


Related articles: