问题描述
我想在用户双击鼠标滚轮后执行一些功能。但是当我双击鼠标滚轮时我无法触发事件侦听器,并且这样的代码无法按我预期的那样工作:
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>