如何让一个MouseWheel事件在jQuery中只有一次? [英] How to get a MouseWheel Event to fire only once in jQuery?

查看:812
本文介绍了如何让一个MouseWheel事件在jQuery中只有一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我每次用户通过鼠标滚轮向上或向下滚动一次功能时,只需要启动一次功能。请参阅: jsFiddle演示。问题是,即使我有e.preventDefault(),该函数仍然多次启动。

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;
}


推荐答案

这个帮助了我:

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);
}

基本上你有一个isMoving变量根据你的动画或其他任何设置你正在进行中。即使用户在一个轻弹中用鼠标滚轮多次滚动,该功能只会触发一次。

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.

这篇关于如何让一个MouseWheel事件在jQuery中只有一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆