簡體   English   中英

是否有替代 JavaScript 中已棄用的 e.which?

[英]Is there an alternative to deprecated e.which in JavaScript?

我是 JavaScript 事件處理的新手,我想在 mousemove 和左鍵單擊 div 元素時觸發一個事件。 我當前的實現是在觸發 mousemove 事件函數時檢查e.which == 1 但是,我已經讀到 e.which 屬性現在已被棄用( https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which )。 我的代碼:

div.addEventListener("mousemove", myEventFunction)

function myEventFunction(e){
    if (e.which == 1){
       //do something
    }

}

有沒有其他方法可以執行此操作?

如果它是鼠標事件,您可以使用event.button

MouseEvent.button只讀屬性指示按下鼠標上的哪個按鈕來觸發事件。

function myEventFunction(e) {
    e = e || window.event;
    if ("buttons" in e) {
        return button;
    }
    var button = e.which || e.button;
    return button;
}

上述函數返回button值。

暫無
暫無

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

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