2017-01-14 13 views
-1

Я попытался переопределить событие колесика мыши 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

Попробуйте это вместо: https://jsfiddle.net/0o1eeL2L/ – icecub

ответ

0
  • См the wheel event reference и использовать соответствующие свойства событий.
  • Также don't use 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(); 
 
    } 
 
}
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>