如何用jQuery来区分鼠标左键和右键

如何用jQuery来区分鼠标左键和右键

jQuery可以用来区分哪个鼠标按钮被点击。这可以用在各种网络应用中,知道某个鼠标按钮可以用来触发某些功能。

使用mousedown()方法:

jQuery中的mousedown()方法可以用来绑定一个事件处理器到默认的 “mousedown “JavaScript事件。这可以被用来触发一个事件。然后,事件对象的’which’属性可以用来检查相应的鼠标按钮。

语法:

$( "#target" ).mousedown(function() {
  alert( "Function to be handles here" );
});

which属性:
which属性有3个值,取决于按下的鼠标按钮。我们可以使用一个switch case来获得相应的值。

  • 鼠标左键为1
  • 鼠标中键为2
  • 鼠标右键为3

示例:

<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>
      How to distinguish left and right 
      mouse click using jQuery?
  </title>
</head>
  
<body>
    <h1 style="color: green">
      GeeksforGeeks
  </h1>
    <b>
      How to distinguish left and 
      right mouse click using jQuery?
  </b>
    <p>You are pressing the :
        <div class="output">
  </div>
  
    <button>
      Click Here to check the mousebutton pressed
  </button>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js">
  </script>
    
    <script type="text/javascript">
        $('button').mousedown(function(event) {
            switch (event.which) {
                case 1:
                    document.querySelector('.output').innerHTML =
                        'Left Mouse Button';
                    break;
                case 2:
                    document.querySelector('.output').innerHTML =
                        'Middle Mouse Button';
                    break;
                case 3:
                    document.querySelector('.output').innerHTML =
                        'Right Mouse Button';
                    break;
                default:
                    break;
            }
        });
    </script>
</body>
  
</html>

输出:
用鼠标左键点击:
如何用jQuery来区分鼠标左键和右键?

用鼠标中键点击:
如何用jQuery来区分鼠标左键和右键?

用鼠标右键点击:
如何用jQuery来区分鼠标左键和右键?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程