【问题标题】:Intercept Mouse Wheel Tilt events?拦截鼠标滚轮倾斜事件?
【发布时间】:2017-01-14 03:55:47
【问题描述】:

我尝试使用以下代码覆盖 Chrome 的鼠标滚轮事件:

// Wheel handler
function wheel(event){
    var ret = true;

    if (event.wheelDelta) {
        // Tilt to the left
        if (event.wheelDeltaX > 0) {
            alert('Left');
            //window.history.back();
            ret = false;
        }
        // Tilt to the right
        if (event.wheelDeltaX < 0) {
            alert('Right');
            //window.history.forward();
            ret = false;
        }
    }

    event.returnValue = ret;
}

// Bind the onmousewheel event to our handler
window.onmousewheel = document.onmousewheel = wheel;

但似乎当我向左/向右倾斜时,什么都没有发生。这个用户脚本有什么问题?谢谢。

【问题讨论】:

标签: javascript jquery mousewheel tampermonkey


【解决方案1】:
  • 参考the wheel event reference 并使用proper 事件属性。
  • 还有,don't use window.on...;始终使用 addEventListener(或 jQuery)。
  • 使用.preventDefault().stopImmediatePropagation() 阻止默认操作。
  • 最后,根据您要阻止的内容,您可能希望/需要绑定到特定元素,而不是 document

这是显示这些技术的工作代码。运行 sn-p 并尝试一下:

var blockedNode = document.getElementById ("blockit");
blockedNode.addEventListener ("wheel", mouseTiltDetect);
//document.addEventListener ("wheel", mouseTiltDetect);

function mouseTiltDetect (zEvent) {
    var blockit = false;

    if (zEvent.deltaX) {
        if (zEvent.deltaX < 0) {        //--  Tilt to the left
            console.log ('Left');
            blockit = true;
        }
        else if (zEvent.deltaX > 0) {   //--  Tilt to the right
            console.log ('Right');
            blockit = true;
        }
    }

    if (blockit) {
        zEvent.preventDefault ();
        zEvent.stopImmediatePropagation ();
    }
}
pre {
    overflow-x: scroll;
    height: 5em;
    border: 1px solid gray;
}
<pre>
Horizontally scroll me using mouse wheel tilt. ... Chuck ipsum. Chuck Norris once tried to wear glasses. The result was him seeing around the world to the point where he was looking at the back of his own head.
</pre>
<hr>
<pre id="blockit">
But you can't scroll this the same way. ... Chuck ipsum. Although it is not common knowledge, there are actually three sides to the Force: the light side, the dark side, and Chuck Norris.
</pre>

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 2021-09-13
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2011-05-08
    • 2010-10-03
    • 2011-07-09
    相关资源
    最近更新 更多