2017-01-14 257 views
-1

我試着用這個代碼重寫瀏覽器的鼠標滾輪事件:攔截鼠標滾輪傾斜事件?

// 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>