2017-01-14 1 views
-1

が、私はこのコードでChromeのマウスホイールイベントを上書きしようとした:Mouse Wheel Tiltイベントを傍受しますか?

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

関連する問題