我有一个wheel事件设置,但是如果您使用的是OS X,则由于本机的弹性效应,该事件将继续触发。

如何防止这种弹性作用?
这是一些代码...

window.addEventListener('wheel',function(){
    pxCount++;
    var starContainer =
    document.getElementById('starContainer').style.left = '-'+50*pxCount+'px';
  });


这是整个项目http://codepen.io/www139/pen/wKbOJz

最佳答案

您可以将侦听器包装在一个防反跳函数中,其目的是在给定的时间限制内,某个操作仅执行一次。

我是这个的粉丝:https://davidwalsh.name/javascript-debounce-function

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};


您可能会这样使用它:

var wheelAction = debounce(function() {
    pxCount++;
    var starContainer =
    document.getElementById('starContainer').style.left = '-'+50*pxCount+'px';
}, 250);

window.addEventListener('wheel', wheelAction);

10-06 00:54