Capturing the “scroll down” event?

后端 未结 10 2183
闹比i
闹比i 2020-12-28 12:17

I\'m designing a very simple web page (HTML only), the only \"feature\" I want to implement is to do something when the user scrolls down the page, is there a way to capture

10条回答
  •  北海茫月
    2020-12-28 13:12

    Check if the user scrolled up and simply return

    window.addEventListener(
      "scroll",
      e => {
        const scrolled = window.scrollY; // Number of pixels the user has scrolled
        let lastScrolled = 0; // Number of pixels the user has scrolled in the last event
    
        // If the user scrolls down, the scrolled value goes up and vice versa
        // So basically
        if (scrolled < lastScrolled) {
          // Then the user scrolled up!
          console.log("GET OUT! YOU SCROLLED UP!");
          // But you should update the lastScrolled value nonetheless
          lastScrolled = scrolled;
          return; // And then get out!
        }
        lastScrolled = scrolled; // The value gets updated in any case
        // And your code goes here
      },
      false
    );
    
    
    

提交回复
热议问题