A few months ago, I had implemented this function. Previously, this effect was written by HTML, css, and JavaScript, and there was a problem: how to prevent page flashing by repeatedly clicking the div slider in a short time.
I used over an hour of last night to overwrite this, and expressed HTML and css directly in JavaScript.
Usage
Add totop. js directly to the HTML page using the script tag.
Alternatively, copy and paste the code in totop. js on the browser control side to see the effect on the current page.
Source code
I have already stored it on GitHub. Click here.
(Function (){
// Add the return slider to the top of the page using JavaScript
Vardiv = document. createElement ("div ");
Div. id = "to-top ";
Div.style.css Text = 'display: none;
Position: fixed;
Bottom: 20px;
Right: 20px;
Z-index: 100;
Cursor: pointer;
Width: 40px;
Height: 40px;
Line-height: 40px;
Border-radius: 3px;
Background: #666;
Text-align: center;
Font-size: 25px;
';
// For convenience, I will use the HTML up Arrow entity here
Div. innerHTML = "& uarr ;";
Document. body. appendChild (div );
// Return to the top animation implementation
// AnimationToTop () has two parameters by default.
// Set the pixel value for each scroll up in the scroll function step. The default value is 5 pixels.
// Set the interval for each call of the rolling function by delay. The default value is 20 ms.
FunctionanimationToTop (step = 5, delay = 20 ){
VarintervalID;
IntervalID = window. setInterval (roll, delay); // timer
Varlength = window. scrollY;
// Scroll up the function
Functionroll (){
Window. scrollTo (0, length-= (step ++ ));
If (length <= 0 ){
ClearInterval (intervalID );
Vartop = document. getElementById ("to-top ");
Top. style. pointerEvents = "auto ";
Top = null;
}
}
}
// Add a click event
Vartop = document. getElementById ("to-top ");
Top. onclick = function (){
Vartop = document. getElementById ("to-top ");
Top. style. pointerEvents = "none ";
Top = null;
AnimationToTop ();
};
// Display the return top button at the appropriate time
Document. addEventListener ("scroll", function (){
Vartop = document. getElementById ("to-top ");
If (window. scrollY <document. body. clientHeight/4 ){
Top. style. display = "none ";
} Else {
Top. style. display = "block ";
}
Top = null;
});
})();