Scroll down to a certain distance to return to the Code instance of the top button, scroll down to return to the top
Scroll down to a certain distance to return to the top of the button code instance:
The buttons at the top of the page are applied on many websites and are very user-friendly. However, some websites may go further, that is, by default, the return button on the top is hidden by default. The button is displayed only after a certain distance is dragged down to the scroll bar. The following describes how to implement this function through code examples.
The Code is as follows:
<! DOCTYPE html>
The above code implements our requirements. The following describes the implementation process of this effect.
I. Implementation principle:
The buttons at the top of the returned results are usually fixed at the bottom right of the webpage. In this way, we can set the button position to position: fixed, and then fix it in the lower right corner by positioning, at the same time, set it to invisible. When the scroll bar is dragged down, when it reaches the specified position, it is set to visible, click the button can be the page to return to the top, when the downward drag distance is less than the specified distance, this button is hidden again. For more information, see the code comments.
Ii. Code comments:
1. $ (function () {}). When the document structure is fully loaded, run the code in the function.
2. $ (window). bind ('scroll ', function () {}), ask the window to register the scroll event handler function, that is, to trigger the specified function when dragging the scroll bar.
3. if ($ (document ). scrollTop () & gt; 200) {$ (". top "). show () ;}: when the distance from the page to the page is more than PX, the button is displayed.
4. else {$ (". top"). hide () ;}, otherwise the button will be hidden.
5. $ (". top "). click (function () {$ ('body, html '). animate ({scrollTop: 0}, 1000) ;}), registers the click event processing function for the button. The event processing function can set the scrollTop attribute value to 0 in 1 second in an animation mode, that is, scroll to the top.
Iii. Related reading:
1. For details about the usage of the bind () function in javascript, see section 1.
2. For details about the scrollTop () function, refer to the scrollTop () function usage section of jQuery.
3. For details about the animate () function, refer to the animate () method section of jQuery.
The original address is: http://www.softwhy.com/forum.php? Mod = viewthread & tid = 14259.
For more information, see: http://www.softwhy.com/jquery/