簡體   English   中英

如何在 JavaScript 上捕獲雙擊鼠標中鍵(滾輪)事件?

[英]How to capture the double click mouse middle button(wheel) event on JavaScript?

我想在用戶雙擊鼠標滾輪后執行一些功能。 但是當我雙擊鼠標滾輪時我無法觸發事件偵聽器,並且這樣的代碼無法按我預期的那樣工作:

https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event

const card = document.querySelector('aside');

card.addEventListener('dblclick', function (e) {
  card.classList.toggle('large');
});

此事件僅在單擊主要 bnutton 時觸發。 我不確定只有在單擊左按鈕或單擊任何按鈕時才應觸發此事件。 任何人都可以向我解釋這一點嗎?

在這里,您可以使用MouseEvent.button

MouesEvent 具有以下數字表示:

0: Main button pressed, usually the left button or the un-initialized state
1: Auxiliary button pressed, usually the wheel button or the middle button (if present)
2: Secondary button pressed, usually the right button
3: Fourth button, typically the Browser Back button
4: Fifth button, typically the Browser Forward button

 document.getElementById('aside').addEventListener('dblclick', function(e) { console.log(e.button); e.preventDefault(); });

另一個例子,如果你使用 jQuery。 jQuery 有event.which屬性,與 MouseEvent 一樣,分配以下數字表示:

event.which also normalizes button presses (mousedown and mouseupevents), 
reporting 1 for left button, 2 for middle, and 3 for right. 
Use event.which instead of event.button.

 $(".aside").live('dblclick', function(e) { if( e.which == 2 ) { alert("middle button"); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM