How to get a MouseWheel Event to fire only once in jQuery?

爱⌒轻易说出口 提交于 2019-12-10 14:51:46

问题


So I want to fire a function only once every time a user scrolls up or down via the Mousewheel. See: jsFiddle Demo. The issue is that even though I have the e.preventDefault(), the function still fires multiple times.

The goal is for the function to fire only once whenever a user scrolls up or down. Similar to this site.

Here is the code that I have so far:

var sq = {};
sq = document;
if (sq.addEventListener) {
    sq.addEventListener("mousewheel", MouseWheelHandler(), false);
    sq.addEventListener("DOMMouseScroll", MouseWheelHandler(), false);
} else {
    sq.attachEvent("onmousewheel", MouseWheelHandler());
}

function MouseWheelHandler() {
    return function (e) {
        var e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        if (delta < 0) {
            /* Scroll Down */
            e.preventDefault();
            console.log("Down. I want this to happen only once");

        } else {
            /* Scroll Up */
            console.log("up. I want this to happen only once");
            e.preventDefault();
        }
        return false;
    }
    return false;
}

回答1:


This has helped me:

var isMoving=false;

$(document).bind("mousewheel DOMMouseScroll MozMousePixelScroll", function(event, delta) {
   event.preventDefault();
   if (isMoving) return;
   navigateTo();
});

function navigateTo(){
   isMoving = true;
   setTimeout(function() {
    isMoving=false;
   },2000);
}

Basically you have a isMoving variable that is set depending on if your animation or whatever you do is in progress. Even though user scrolls multiple times with mousewheel in one "flick", the function fires only once.




回答2:


   ​$(document).ready(function(){
var up=false;
var down=false;
        $('#foo').bind('mousewheel', function(e){
            if(e.originalEvent.wheelDelta /120 > 0 && up=false)  {
up=true;
down=false;
                $(this).text('scrolling up !');
            }
            elseif(e.originalEvent.wheelDelta /120 > 0 && down=false){
down=true;
up=false;
                $(this).text('scrolling down !');
            }
        });
    });

And here is a plug in you can use it



来源:https://stackoverflow.com/questions/19123288/how-to-get-a-mousewheel-event-to-fire-only-once-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!