【问题标题】:How to capture the double click mouse middle button(wheel) event on JavaScript?如何在 JavaScript 上捕获双击鼠标中键(滚轮)事件?
【发布时间】:2021-07-28 15:22:24
【问题描述】:

我想在用户双击鼠标滚轮后执行一些功能。但是当我双击鼠标滚轮时无法触发事件侦听器,并且这样的代码无法按预期工作:

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');
});

此事件仅在单击主按钮时触发。 我不确定仅在单击左键或单击任何按钮时才应触发此事件。谁能给我解释一下?

【问题讨论】:

    标签: javascript html dom-events mouseevent mousewheel


    【解决方案1】:

    这里可以使用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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 2016-09-06
      • 2011-05-24
      • 1970-01-01
      • 2012-12-24
      相关资源
      最近更新 更多