JS implementation of a key back to the top function sample code

  • 2020-03-26 21:44:20
  • OfStack

1. Basic preparation:

The scrollTop() method returns or sets the vertical position of the scroll bar for the matching element.

Scroll top offset is the offset of the scroll bar relative to its top.

If the method does not set parameters, it returns the offset in pixels at the top of the relative scroll bar.


$(the selector). ScrollTop (offset)


ToggleClass () toggles one or more classes that set or remove the selected element.

For example, set and remove all < P> Element "main" class to switch:


The setInterval() method can call a function or evaluate an expression for a specified period of milliseconds.

The setInterval() method calls the function until clearInterval() is called or the window is closed. The ID value returned by setInterval() can be used as an argument to the clearInterval() method.


The scrollTo() method scrolls content to the specified coordinates.

ScrollTo (xpos, ypos)

Parameters to describe
Xpos required. The x coordinate of the document to be displayed in the upper left corner of the document display area of the window.
Ypos required. The y coordinate of the document to be displayed in the upper left corner of the document display area of the window.

This section of the implementation of a key up the code as follows:
var topbtn = $("#totop");  Button elements that want to be one-click up  
var lastScroll = 0; 
topbtn.css("display", "none"); 

window.onscroll = function(){ onscroll As for html5 The properties of the  
var top = $(window).scrollTop(); The initial are 0 

if(top > 0){ 
topbtn.css("display", ""); 
if(top == 0){ If it is the start state, the up icon is not displayed  
topbtn.css("display", "none"); 

topbtn.click(function(){  Click on the event  
var scrollTop = 0; 
var curPos = $(window).scrollTop(); Now the position of the scroll bar  
topbtn.addClass("movingtotop");  Show another picture during the campaign  
var step = Math.abs(scrollTop - curPos) / 200 ; 
var tid = setInterval(function() { Call again and again, frame to draw  
topbtn.toggleClass("movingtotop");  A nice piece of code, with the element attribute Settings and delete alternate, so that there is a dynamic flicker effect  
if (curPos > scrollTop + 14) { 
curPos -= step; 
step = step * 1.05; Speed up  
window.scrollTo(0, curPos); 
} else if (curPos <= scrollTop + 14){ Jump to the starting position  
window.scrollTo(0, scrollTop); 
clearInterval(tid);  Closed loop  
}, 0.01); 

Related articles: