讀jQuery之七 判斷點擊了滑鼠哪個鍵的代碼

來源:互聯網
上載者:User

jQuery丟棄了標準的 button 屬性採用 which,這有點讓人費解。

which 是Firefox引入的,IE不支援。which的本意是擷取鍵盤的索引值(keyCode)。

jQuery中的which即可以是鍵盤的索引值,也可以是滑鼠的索引值。
即當判斷使用者按下鍵盤的哪個鍵時可以使用which,當判斷使用者按下滑鼠的哪個鍵時也可以用which。它一舉兩用了。
源碼
複製代碼 代碼如下:
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}

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

標準的button採用0,1,2表示滑鼠的左,中,右鍵。jQuery的which則使用用1,2,3。

還有一點讓人不爽的是jQuery文檔 event.which 中並沒有提到which可以表示滑鼠按索引值,只提到了表示鍵盤按索引值。

源碼中的注釋也讓人誤解。
複製代碼 代碼如下:
// Add which for click: 1 === left; 2 === middle; 3 === right

注意這裡說的是click ,很容易讓人使用click 事件,但實際上click事件中擷取是錯誤的。
下面就用 click 事件試試:
複製代碼 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<script src="http://code.jquery.com/jquery-1.6.1.js"></script>
<script type="text/javascript">
$(document).click(function(e){
alert(e.which);
})
</script>
</head>
<body>
</body>
</html>

測試結果
IE6/7/8 IE9 Firefox4 Chrome12 Safari Opera
點擊左鍵 0 1 1 1 1(不停彈出alert) 1
點擊中鍵 不響應 2 2 2 2(不停彈出alert) 不響應
點擊右鍵 僅彈出右鍵菜單 僅彈出右鍵菜單 3,彈出右鍵菜單 僅彈出右鍵菜單 僅彈出右鍵菜單 僅彈出右鍵菜單

可以看到使用 click 事件並不能按照jQuery設想的那樣左,中,右鍵對應的1,2,3值。各瀏覽器下均不一致,且右鍵根本擷取不到,Safari中還不停的彈出alert。

因此,應該使用 mousedown / mouseup 事件則達到jQuery的設想。jQuery的注釋誤導了人。

此外即使使用 mousedown / mouseup 事件,Opera中也無法擷取中鍵的值。Opera的噁心做法令jQuery也無能為力。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.