简体   繁体   中英

How to cancel a scroll event after N pixels have been scrolled

inputs :

  • 1 scroll down event scrolls 100 pixels.
  • An HTML element is 5 pixels below the bottom of the page. It is not on screen.
  • A Javascript function detects when at least 1 pixel of the HTML element is on screen, and :
    • automatically scrolls the page so that the element is fully on screen.
    • prevent other scroll events during the animation

events :

  • the user does 1 scroll-down event (refered below as "the scroll event").

expected result :

  • After 6 pixels scrolled - when 1px of the element is visible - the scroll event is CANCELLED and the javascript function initiates the automatic scroll.

actual result :

  • The other scroll events are correctly prevented, but it looks like the first scroll event and the automatic scroll are in conflict as long as the scroll event hasn't finished its 100px scroll (it looks choppy).

I did try to do "overflow:hidden" on the "body" during the animation, but this does not cancel the scroll event, which still continues to scroll the page after the animation of the automatic scroll is completed (specifically using a laptop trackpad).

Any ideas ? Thx !

PS: I would appreciate native javascript answers please.

You could use window.pageYOffset

Here is an example: The code within the if statement only runs within the first 100px from top of the page

window.addEventListener("scroll", function(){
    if(window.pageYOffset < 100) {
        console.log("hi there");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM