【问题标题】:mousewheel event is too fast. How to disable it鼠标滚轮事件太快。如何禁用它
【发布时间】:2014-06-21 20:25:42
【问题描述】:

我正在尝试在我的网站 udowalzfinal.umatechcorner.com 中引入类似 hugeinc.com 的效果

我做了以下

$(window).on({
'DOMMouseScroll mousewheel': ScrollBegin
});

var delta = 0;
var scrollThreshold = 10;

        function ScrollBegin(e) {

        // --- Scrolling up ---
    if (e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0) { 
        delta--;
                    console.log(delta);
        if ( Math.abs(delta) >= scrollThreshold) {
         timer = setTimeout(function () {
                    MoveScreen('up');                        
                }, 800);
        clearTimeout(timer);
    }
}

// --- Scrolling down ---
else {

    delta++;
 console.log(delta); 
    if (delta >= scrollThreshold) {
     timer = setTimeout(function () {
                    MoveScreen('down');
                    clearTimeout(timer);

                }, 800);
    }
}

// Prevent page from scrolling
return false;    
        }

我不知道为 scrollThreshold 设置什么值。

mousewheel 事件被引发并 ScrollBegin 被执行。但这在 IE 中太慢了,而在带有 Apple Mouse 的 Safari 中太快了。

每次鼠标滚轮移动都会引发鼠标滚轮事件。就我而言,当我滚动一次鼠标滚轮时,它会引发 10 次事件。我怎样才能禁用这 9 个事件并且只处理一次。

How to get a MouseWheel Event to fire only once in jQuery? 文章没有解决我的问题。这仅支持向上移动一次然后向下移动一次。但我的页面中有 5 张幻灯片。

有人可以帮忙吗?

【问题讨论】:

标签: javascript jquery mousewheel


【解决方案1】:

您可能应该使用debouncer

//Debouncer functions add a delay between an event and a reaction, so scaling and scrolling don't evoke a function dozens of times.
function debouncer(func, timeout) {
    var timeoutID , timeout = timeout || 200;
    return function () {
        var scope = this , args = arguments;
        clearTimeout( timeoutID );
        timeoutID = setTimeout( function () {
            func.apply( scope , Array.prototype.slice.call( args ) );
        } , timeout );
    };
}

这是一个通用功能。像这样使用它:

jQuery(window).scroll(debouncer(function(){
    //Call your scroll handler here.
}));

要真正微调延迟,请添加一个 cecond 参数,例如:

jQuery(window).scroll(debouncer(function(){
    //Call your scroll handler here.
}), 600);

【讨论】:

  • 我宁愿做setTimeout(fn.apply.bind(fn, this, argsCopy), interval);
【解决方案2】:

你想看看像 Underscore.js 的 Debounce 函数这样的东西。您可以通过在页面上添加下划线来直接使用 debounce(这不是一个坏主意),也可以自己实现。还有节流阀,其工作方式略有不同;这是两者的示例:

http://goo.gl/jEl9lA

【讨论】:

  • 谢谢。这是完美的。我对我的代码做了一些改动,一切正常
  • 那是完美的@Paul。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-05
  • 1970-01-01
相关资源
最近更新 更多