如何在鼠标按下时检测到鼠标右键事件?

35

我正在更新/调试并扩展我的可拖动脚本的功能,我需要能够实现以下结果:

whatever.onRightMouseButtonMousedown = preventDefault();
我做了许多研究,但是找不到解决方案。然而,我知道这是可能的,因为当我使用jquery-ui可拖动时,它会阻止用鼠标右键按下时拖动元素的能力。我想模仿这种能力,并学习它的实现方式,以便在需要时立即实现。
注:请不要告诉我如何使用jquery或jquery-ui可拖动(我已经熟悉它),我想学习它们是如何实现的,或者如何实现检测鼠标右键按下的功能,以便防止使用鼠标右键拖动元素。

这不是重复的问题。该问题特别询问如何在不使用jQuery的情况下完成它。 - person0
4个回答

44

通常当您有任何类型的鼠标事件时,您只希望它仅在一种类型的鼠标单击上操作。因此,传递给您的回调函数的事件具有一个属性,允许您区分不同类型的单击。

这些数据通过事件数据的button属性传递回来。请参见MDN以查找表示什么数据的值。

因此,您不需要禁用右键单击,而是仅为左键单击启用功能。以下是一个[糟糕的]示例:

element.onmousedown = function(eventData) {
  if (eventData.button === 0) {
      alert("From JS: the (left?) button is down!")
  }
}  

在jQuery中的等效写法是:

$("div").mousedown(function(eventData) {
    if (eventData.which === 0) {
        alert("From JQuery: which=" + eventData.which)
    }
});

请注意,如果您不使用jQuery,则返回的值在不同浏览器之间会有所不同。使用jQuery 统一了跨浏览器的值,左键为1,中键为2,右键为3:

 element.onmousedown = function(eventData) {
   if (eventData.button === 0) {
     console.log("From JS: the (left?) button is down!")
   }
 }

 $("#element").ready(function() {
   $("div").mousedown(function(de) {
     console.log("From JQuery: which=" + de.which);
   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element" style="width: 100px; height: 100px; background-color: blue" />


2
谢谢,实际上在回来查看您的评论之前我已经解决了这个问题,我只是想补充一下,为了使它在各种浏览器(至少是现代浏览器)中正常工作,您只需要检查 event.whichevent.button,这就是我最终解决它的方法: if (evt.which === 3 || evt.button === 2) {evt.preventDefault(); - person0
5
左键的 event.button === 0,滚轮是 event.button === 1,右键是 event.button === 2。详见 https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/button#返回值。 - F Lekschas

11

HTML、Javascript和演示:

function mouseDown(e) {
  e = e || window.event;
  switch (e.which) {
    case 1: alert('left'); break;
    case 2: alert('middle'); break;
    case 3: alert('right'); break; 
  }
}
<a href="#" onmousedown="mouseDown(event);">aaa</a>


3

这并不是很简单。Quirksmode.org有一篇关于事件属性的文章

在“哪个鼠标按钮被点击了?”/“右键单击”下查看。它因浏览器而异。


11
我知道这是一段时间以前的内容,但我点击了那个链接,看到了“甚至连IE6也不支持”这一行字,意味着这篇文章非常古老。 - J S

0

时按下几个鼠标按钮也是可能的。

为了知道哪些鼠标按钮被按下,
必须使用布尔代数运算符!

按照以下步骤进行:

const
  divX   = document.querySelector('#divX')
, Buttons_status = 
    { left       : { key : 0b00001, isDown: false }  // Primary button   (usually the left button)
    , right      : { key : 0b00010, isDown: false }  // Secondary button (usually the right button)
    , center     : { key : 0b00100, isDown: false }  // Auxiliary button (usually the mouse wheel button or middle button) 
    , bt_Back    : { key : 0b01000, isDown: false }  // 4th button (typically the "Browser Back" button)
    , bt_Forward : { key : 0b10000, isDown: false }  // 5th button (typically the "Browser Forward" button) 
    }

function testingButtons(e)
  {
  let DownBtns = ''
  for (let bt in Buttons_status )
    {
    Buttons_status[bt].isDown = !!(Buttons_status[bt].key & e.buttons )

    if (Buttons_status[bt].isDown) DownBtns += ' ' + bt
    }
  console.log ('Down buttton(s) :', DownBtns ? DownBtns : 'none' ) 
  // console.log( Buttons_status )
  }
 
divX.onmousedown = testingButtons
divX.onmouseup   = testingButtons

document.body.oncontextmenu =_=> false  // for clear testing
#divX {
  display    : inline-block;
  background : lawngreen;
  margin     : .7em;
  padding    : 1em .7em;
  }
button {
  display        : inline-block;
  vertical-align : top;
  }
.as-console-wrapper {
  max-height: 1.6em !important; 
  }
<div id="divX"> 
  Do a mouse click anywhere here.
  <br><br>
  You can activate several buttons
  <br>
  <small>[do not release the previous button(s) when you press a new one]</small>
  <br><br>
  <small>(then realease just one of them)</small>
</div>

<button onclick="console.clear()">Clear</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接