如何在mousedown上检测到rightmouse按钮事件? [英] How can I detect a rightmouse button event on mousedown?

查看:238
本文介绍了如何在mousedown上检测到rightmouse按钮事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am updating/debugging and expanding the capabilities of my draggable script and I need to be able to achieve the following result:

whatever.onRightMouseButtonMousedown = preventDefault();

我做了很多研究但没有用,但是,我知道有可能做到这是因为当我使用jquery-ui draggable时,它会阻止您在使用鼠标右键进行拖动时拖动元素的能力。我想模仿这种能力,并了解它的工作原理,以便我可以根据需要现在和将来实施。

I have done a lot of research to no avail, however, I know that it is possible to do this because when I use jquery-ui draggable, it prevents the ability to drag elements when you mousedown with the right mouse button. I want to mimic this ability, and learn how it works so that I can implement it now and in the future as needed.

注意:请不要给关于如何使用jquery或jquery-ui draggable的信息(我已经熟悉它),我想了解它们是如何实现的,或者如何用鼠标右键实现mousedown的检测,这样我才能使用鼠标右键阻止元素被拖拽。

推荐答案

通常当你有任何类型的鼠标事件时,你只想让它只在一种鼠标点击上运行。因此,传递给回调的事件有一个属性,可以让您区分点击类型。

Normally when you have any kind of mouse event, you'll want to have it only operate on one type of mouse click. Therefore, the events passed to your callbacks have a property which allow you to distinguish between types of clicks.

此数据通过按钮事件数据的属性。请参阅 MDN ,了解哪些值代表哪些数据。

This data is passed back through the button property of the event data. See MDN for finding out what values represent what data.

因此,您不会禁用右键单击,而是仅为左键单击启用您的功能。这是一个[差]的例子:

Therefore, you don't disable the right click, you instead only enable your functionality for the left click. Here's a [poor] example:

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

jQuery中的等价物是:

the equivalent in jQuery is:

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

请注意,如果您不使用jquery,则返回的值会因浏览器而异。 jQuery 统一浏览器的值,左侧为1,中间为2,右侧为3:

Note that if you don't use jquery, the values returned will be different across browsers. jQuery unifies the values across browsers, using 1 for left, 2 for middle, 3 for right:

 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" />

这篇关于如何在mousedown上检测到rightmouse按钮事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆