2017-07-31 102 views
1

例子:如何使用javascript MouseEvents同時左右點擊鼠標中鍵不同點擊?

document.querySelector("body").addEventListener("mousedown", (e) => console.log(e.button, e.buttons)); 

如果你把在瀏覽器的控制檯... 中間點擊日誌1,4和左,右按鍵,同時記錄1,4太多。

瀏覽器是否會反彈點擊並報告它們的延遲?我怎樣才能區分這兩件事?

+0

我不認爲鼠標事件經過深思熟慮非常好。 「左」和「右」按鈕的概念是不恰當的,應該是「初級」,「次級」等等。我從CAD電​​腦開始使用我們所謂的光標(類似於鼠標,但用於高精度數字化),上面有9個按鈕。我認爲你能做的最好的是[* button *](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button)屬性,它返回一個從0到4的值(但檢查支持,這是不一致的)。 – RobG

回答

0
var buttonsMap = { 
    1 : "primary", 
    2 : "contextmenu", 
    3 : "primary + contextmenu", 
    4 : "middle", 
    5 : "primary + middle", 
    6 : "contextmenu + middle" 
} 


document.body.addEventListener("mousedown", (e) => { 

    console.log(buttonsMap[e.buttons]); // Here you go 

    // What you could do: 
    if(/3|5|6/.test(e.buttons)) { 
    console.log("DOUBLE!!!"); 
    } else { 
    console.log("single"); 
    } 

}); 

jsBin demo

https://w3c.github.io/uievents/#dom-mouseevent-buttons

+0

僅有代碼的答案沒有幫助。您應該包含相關資源的鏈接,例如[* W3C UI Events spec *](https://w3c.github.io/uievents/#widl-MouseEvent-buttons)和[* MDN MouseEvent.buttons *](https:/ /developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons)。 0在哪裏? – RobG

相關問題