문제

As I have heard, different browsers assign different keycode values to mouse buttons on mousedown event. I have tried this in Chrome and it worked:

$('a').mousedown(function(f) {
    if (f.which == 2) {
        alert("You clicked the wheel")
    }
})​

However, I'm afraid some browsers will fail to recognize the mousewheel's keycode being 2 and will confuse it with the other mouse buttons, thus crashing the code. My question is if there is any way to reset these values so I can use the new ones I provide so all the browsers will know what the numbers represent exactly.

도움이 되었습니까?

해결책

With jQuery, 2 will represent the mouse wheel or the «middle click button». You cannot change these values, but you also do not have to, because if you get something other than 2 on f.which, it's most likely not the mousewheel that was downed.

There are two mouse event models, one by the W3C and one by Microsoft. Browsers (also including IE7 and IE8) implement the W3C standard.

UPDATE

In Javascript, the mouse event button is not normalized because of the two different standards. Actually, jQuery normalizes the which on the mouse event:

// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
  event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}

다른 팁

According to W3C its values should be:

  • Left button – 0
  • Middle button – 1
  • Right button – 2

According to Microsoft its values should be:

  • Left button – 1
  • Middle button – 4
  • Right button – 2

But you don't have to think about it (cross browser issue), leave it on jQuery, in every browser which will return the same result

$('a').mousedown(function(e) {
    if( (e.which == 1) ) {
        alert("left button");
    }if( (e.which == 3) ) {
        alert("right button");
    }else if( (e.which == 2) ) {
        alert("middle button"); 
    }
})​;

DEMO. (Tested in IE, Chrome and FF)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top