[英]Catching a middle mouse button click in an Angular 6 directive
I made a custom directive in which I want to catch middle mouse button click events.我做了一个自定义指令,我想在其中捕获鼠标中键单击事件。 I figured it'd just be a normal click event, and to go from there but it's only fired when the left mouse button is clicked.
我认为这只是一个普通的点击事件,然后从那里开始,但只有在单击鼠标左键时才会触发。
@HostListener('click', ['$event']) onClick($event){
console.info('Click event fired', $event);
}
Any suggestions?有什么建议?
Thanks!谢谢!
You need to handle the mouseup
or mousedown
event which capture all mouse clicks, rather than just the left button.您需要处理捕获所有鼠标点击的
mouseup
或mousedown
事件,而不仅仅是左键。
@HostListener('mouseup', ['$event']) onClick($event){
console.info('Click event fired', $event);
if($event.which === 2)
console.info('Middle mouse button clicked');
}
The $event
variable returned will be a MouseEvent .返回的
$event
变量将是MouseEvent 。 You can check the which
property to see which button was pressed.您可以检查
which
属性以查看按下了哪个按钮。 If $event.which === 2
then it will be the middle mouse button.如果
$event.which === 2
那么它将是鼠标中键。
Here is a live example I created so you can see it in action.这是我创建的一个活生生的例子,所以你可以看到它的实际效果。
Try mousedown event and catch the middle button click尝试 mousedown 事件并捕捉中间按钮的点击
@HostListener('mousedown', ['$event']) onClick(e) {
console.log(e.which)
if (e.which === 2) {
console.log('Middle button ==> ', e.which)
e.preventDefault();
}
}
Updated answer for 2020 2020 年的更新答案
The "which" attribute from MouseEvent been deprecated. MouseEvent 中的“which”属性已被弃用。 The currently up to date way to figure out which button was clicked is the "button" attribute.
当前确定点击了哪个按钮的最新方法是“按钮”属性。
assuming "event" is a "MouseEvent", event.button is a number which can be interpreted as follows:假设“事件”是“鼠标事件”,则 event.button 是一个数字,可以解释如下:
Adapting from @alex-wiese's answer, and depending on the input device, you'd get:改编自@alex-wiese 的答案,根据输入设备,您会得到:
@HostListener('mouseup', ['$event']) onClick($event){
console.info('Click event fired', $event);
if($event.button === 1)
console.info('Middle mouse button clicked');
}
Source: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button来源: https : //developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.