题意:"在 JavaScript 中,有没有可以替代已弃用的 `e.which` 的方法?"
问题背景:
Im new to JavaScript event handling, I would like to trigger an event upon mousemove and left-click on a div element. My current implementation is to check that e.which == 1
when I trigger the mousemove event function. However, I have read that the e.which property is now deprecated (UIEvent: which property - Web APIs | MDN). My code:
"我是 JavaScript 事件处理的新手,我想在鼠标移动和左键点击一个 div 元素时触发一个事件。当前的实现是通过在触发 `mousemove` 事件时检查 `e.which == 1`。然而,我读到 `e.which` 属性已经被弃用(UIEvent: which property - Web APIs | MDN)。我的代码如下:"
div.addEventListener("mousemove", myEventFunction)
function myEventFunction(e){
if (e.which == 1){
//do something
}
}
Is there any alternative to perform this operation?
"是否有替代方法来执行此操作?"
问题解决:
You can use event.button if it is gonna be a mouse event.
“如果是鼠标事件,你可以使用 `event.button`。”
The
MouseEvent.button
read-only property indicates which button was pressed on the mouse to trigger the event.
function myEventFunction(e) {
e = e || window.event;
if ("buttons" in e) {
return button;
}
var button = e.which || e.button;
return button;
}
The above function returns the button
value.
“上述函数返回的是 `button` 值。”