2012-07-11 49 views
2

正如我所聽到的,不同的瀏覽器在mousedown事件中爲鼠標按鈕分配不同的鍵碼值。我曾嘗試在Chrome this和它的工作:更改鼠標鍵碼 - jquery

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

不過,恐怕有些瀏覽器將無法識別鼠標滾輪的鍵碼爲2,並且將與其他鼠標按鈕混淆,從而崩潰的代碼。我的問題是,如果有任何方法來重置這些值,所以我可以使用我提供的新的值,因此所有的瀏覽器都會知道數字代表的是什麼。

回答

1

使用jQuery,2將代表鼠標滾輪或「中間點擊按鈕」。您無法更改這些值,但您也不必這樣做,因爲如果您在f.which之外獲得了2以外的其他值,則很可能不是鼠標滾輪被擊倒。

還有two mouse event models, one by the W3C and one by Microsoft瀏覽器(也包括IE7和IE8)實現the W3C standard

UPDATE

在Javascript中,鼠標事件按鈕是因爲兩個不同的標準不歸。事實上,jQuery的規範了其上的鼠標事件:

// 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))); 
} 
+2

值2代表* right *鼠標按鈕。 – MaxArt 2012-07-11 19:50:09

+0

@MaxArt你見過我的jsfiddle嗎?在我的Chrome瀏覽器中,它代表中間按鈕。 – menislici 2012-07-11 19:53:04

+0

@MaxArt你是對的,謝謝。 – 2012-07-11 19:58:44

3

根據W3C其值應爲:

  • 左鍵 - 0
  • 中間按鈕 - 1
  • 右按鈕 - 2

根據Microsoft的規定,其值應爲:

  • 左鍵 - 1
  • 中間按鈕 - 4
  • 右按鈕 - 2

但你不必去想它(跨瀏覽器的問題),把它留在jQuery,在每一個瀏覽器which將返回相同的結果

$('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.(在IE,鉻和FF測試)