How can I determine the direction of a jQuery scroll event?

后端 未结 25 1903
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 22:24

I\'m looking for something to this effect:

$(window).scroll(function(event){
   if (/* magic code*/ ){
       // upscroll code
   } else {
      // downscrol         


        
25条回答
  •  半阙折子戏
    2020-11-21 23:02

    Scroll Event

    The scroll event behaves oddly in FF (it is fired a lot of times because of the smoothness scrolling) but it works.

    Note: The scroll event actually is fired when dragging the scroll bar, using cursor keys or mousewheel.

    //creates an element to print the scroll position
    $("

    ").appendTo("body").css({ padding: "5px 7px", background: "#e9e9e9", position: "fixed", bottom: "15px", left: "35px" }); //binds the "scroll" event $(window).scroll(function (e) { var target = e.currentTarget, self = $(target), scrollTop = window.pageYOffset || target.scrollTop, lastScrollTop = self.data("lastScrollTop") || 0, scrollHeight = target.scrollHeight || document.body.scrollHeight, scrollText = ""; if (scrollTop > lastScrollTop) { scrollText = "scroll down"; } else { scrollText = "scroll up"; } $("#test").html(scrollText + "
    innerHeight: " + self.innerHeight() + "
    scrollHeight: " + scrollHeight + "
    scrollTop: " + scrollTop + "
    lastScrollTop: " + lastScrollTop); if (scrollHeight - scrollTop === self.innerHeight()) { console.log("► End of scroll"); } //saves the current scrollTop self.data("lastScrollTop", scrollTop); });


    Wheel Event

    You also may take a look at MDN, it exposes a great information about the Wheel Event.

    Note: The wheel event is fired only when using the mousewheel; cursor keys and dragging the scroll bar does not fire the event.

    I read the document and the example: Listening to this event across browser
    and after some tests with FF, IE, chrome, safari, I ended up with this snippet:

    //creates an element to print the scroll position
    $("

    ").appendTo("body").css({ padding: "5px 7px", background: "#e9e9e9", position: "fixed", bottom: "15px", left: "15px" }); //attach the "wheel" event if it is supported, otherwise "mousewheel" event is used $("html").on(("onwheel" in document.createElement("div") ? "wheel" : "mousewheel"), function (e) { var evt = e.originalEvent || e; //this is what really matters var deltaY = evt.deltaY || (-1 / 40 * evt.wheelDelta), //wheel || mousewheel scrollTop = $(this).scrollTop() || $("body").scrollTop(), //fix safari scrollText = ""; if (deltaY > 0) { scrollText = "scroll down"; } else { scrollText = "scroll up"; } //console.log("Event: ", evt); $("#test").html(scrollText + "
    clientHeight: " + this.clientHeight + "
    scrollHeight: " + this.scrollHeight + "
    scrollTop: " + scrollTop + "
    deltaY: " + deltaY); });

提交回复
热议问题