我尝试使用以下代码覆盖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;
但似乎当我向左/向右倾斜时,没有任何反应。这个用户的错误是什么?感谢。
答案 0 :(得分:0)
wheel
event reference并使用正确的事件属性。 window.on...
;总是使用addEventListener
(或jQuery)。.preventDefault()
和.stopImmediatePropagation()
来屏蔽默认操作。document
。这是显示技术的工作代码。运行代码段然后尝试:
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 ();
}
}
&#13;
pre {
overflow-x: scroll;
height: 5em;
border: 1px solid gray;
}
&#13;
<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>
&#13;