JavaScript implementation back to top effect

Keywords: Javascript less IE

Copy Taobao back to top effect

Requirement: when the scroll bar reaches a certain position, the sidebar is fixed at a certain position, and then when it slides down to a certain position, the back to top button will be displayed. After clicking the button, the page will slide to the top dynamically, from fast to slow.

Train of thought:

1. js code can only be executed after the page is loaded

You can write js code at the bottom (this is used in the back to top example)

If you want to write on the top, you can use the following two kinds:

      ①window.onload = function() {...}

   ②window.addEventListener('load', function() {...})

2. Get the elements needed

3. Bind scroll event scroll

Make sidebar fixed when user rolls to banner module

1 if(window.pageYOffset >= bannerTop) {    // window.pageYOffset The distance the screen is rolled up
2     sliderbar.style.position = 'fixed';   // When the user rolls to banner Make sidebar fixed when module
3     sliderbar.style.top = sliderbarTop + 'px'; 
4 } else {
5     sliderbar.style.position = 'absolute';
6     sliderbar.style.top = '300px';
7 }

Display the back to top button when the user scrolls to the main module

1 if(window.pageYOffset >= mainTop) {    // When the user rolls to main Show back to top button when module
2     goBack.style.display = 'block';
3 } else {
4     goBack.style.display = 'none';
5 }

4. Bind click event

Click the back to top button, and the page will slide to the top dynamically, from fast to slow

1 sliderbar.addEventListener('click', function() {
2     animate(window, 0);
3 })

5. About animation function (obj, target, callback)

Here, obj object is window; target target target location is 0; callback is callback function, which can be ignored without parameters

Set a timer, setInterval();

Declare a step as the step value, the value is the difference between the top position and the current scroll bar position divided by 10 (the step will be smaller and smaller, the rolling speed will be slower and slower, realizing the speed of the scroll bar to slide up from fast to slow)

var step = (target - window.pageYOffset) / 10;

However, step is not always an integer. When step is not an integer, you can let the scroll bar go forward and throw it. The scroll bar can slide up and down, so the step may be greater than or less than zero. Greater than zero rounding up, less than zero rounding down

step = step > 0 ? Math.ceil(step) : Math.floor(step);

window.scroll(x, y) scrolls to a specific location in the document, and the timer will slide up a little every time it calls the function

window.scroll(0, window.pageYOffset + step);

Judge whether the animation is completed. If it is completed, turn off the timer clearInterval();

1 if(window.pageYOffset == target) {  // When the page comes back to the top(The animation is finished) Clear timer
2     clearInterval(obj.timer);
3     //  Determine whether the callback function is passed
4     /* if(callback) { 
5         callback();
6     } */
7     // It can be abbreviated to the following. &&Is the short circuit operator, exists callback(That is, the first formula is true)Will continue callback()
8     callback && callback();
9 }

 

The detailed code is as follows:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6     <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7     <title>Return to top effect</title>
  8     <style>
  9         .slider-bar {
 10             position: absolute;
 11             left: 47%;
 12             top: 300px;
 13             margin-left: 600px;
 14             width: 45px;
 15             height: 130px;
 16             background-color: pink;
 17             cursor: pointer;
 18         }
 19         .w {
 20             width: 1100px;
 21             margin: 10px auto;
 22         }
 23         .header {
 24             height: 150px;
 25             background-color: purple;
 26         }
 27         .banner {
 28             height: 250px;
 29             background-color: skyblue;
 30         }
 31         .main {
 32             height: 1000px;
 33             background-color: yellowgreen;
 34         }
 35         span {
 36             display: none;
 37             position: absolute;
 38             bottom: 0;
 39         }
 40     </style>
 41 </head>
 42 <body>
 43     <div class="slider-bar">
 44         <span class="goBack">Return to the top</span>
 45     </div>
 46     <div class="header w">Head region</div>
 47     <div class="banner w">banner region</div>
 48     <div class="main w">Main part</div>
 49 
 50     <script>
 51         // querySelector() Method returns the first element matching the specified selector (), which must be a string
 52         var sliderbar = document.querySelector('.slider-bar');
 53         var banner = document.querySelector('.banner');
 54         var bannerTop = banner.offsetTop; // banner Length of module from top
 55         var sliderbarTop = sliderbar.offsetTop - bannerTop; // Length from top of sidebar fixed
 56 
 57         var main = document.querySelector('.main');
 58         var goBack = document.querySelector('.goBack');
 59         var mainTop = main.offsetTop;  // main Length of module from top
 60         
 61         // scroll Executed when a scrolling event occurs on the screen
 62         document.addEventListener('scroll', function() {
 63             if(window.pageYOffset >= bannerTop) {    // window.pageYOffset The distance the screen is rolled up
 64                 sliderbar.style.position = 'fixed';   // When the user rolls to banner Make sidebar fixed when module
 65                 sliderbar.style.top = sliderbarTop + 'px'; 
 66             } else {
 67                 sliderbar.style.position = 'absolute';
 68                 sliderbar.style.top = '300px';
 69             }
 70             
 71             if(window.pageYOffset >= mainTop) {    // When the user rolls to main Show back to top button when module
 72                 goBack.style.display = 'block';
 73             } else {
 74                 goBack.style.display = 'none';
 75             }
 76             
 77         });
 78         sliderbar.addEventListener('click', function() {
 79             animate(window, 0);
 80         })
 81 
 82         /* Animation function:
 83          *  obj Animated objects (in this case, window)
 84          *  target Target location (top)
 85          *  callback Callback function (do not execute without parameters)
 86          */
 87         function animate(obj, target, callback) {
 88             clearInterval(obj.timer);  // First, clear the timer to ensure that only one timer is executing, so as not to appear bug
 89             obj.timer = setInterval(function() {
 90                 // window.pageYOffset Distance from top (negative)
 91                 var step = (target - window.pageYOffset) / 10;  // step Step size (let the page speed slowly slide up)
 92                 step = step > 0 ? Math.ceil(step) : Math.floor(step); // step It's not always an integer. Greater than zero round up,Less than zero rounding down
 93                 if(window.pageYOffset == target) {  // When the page comes back to the top(The animation is finished) Clear timer
 94                     clearInterval(obj.timer);
 95                     //  Determine whether the callback function is passed
 96                     /* if(callback) { 
 97                         callback();
 98                     } */
 99                     // It can be abbreviated to the following. &&Is the short circuit operator, exists callback(That is, the first formula is true)Will continue callback()
100                     callback && callback();
101                 }
102                 // window.scroll(x, y) Scroll to document specific location
103                 window.scroll(0, window.pageYOffset + step);
104             }, 15);
105         }
106     </script>
107 </body>
108 </html>

 

 

Posted by rowanparker on Tue, 26 Nov 2019 12:59:23 -0800