如何使用jQuery获得鼠标点击按钮?

$('div').bind('click', function(){
    alert('clicked');
});

这是由右键和左键点击触发的,有什么方法可以捕捉到鼠标右键点击?如果存在以下内容,我会很高兴:

$('div').bind('rightclick', function(){ 
    alert('right mouse button is pressed');
});

当前回答

编辑:我在jQuery 1.7或以上版本中使用.on()将其更改为动态添加的元素:

$(document).on("contextmenu", ".element", function(e){
   alert('Context Menu event has fired!');
   return false;
});

演示:jsfiddle.net/Kn9s7/5

[原文开始]这对我来说是有效的:

$('.element').bind("contextmenu",function(e){
   alert('Context Menu event has fired!');
   return false;
}); 

以防你有多种解决方案^^

编辑:Tim Down提出了一个很好的观点,它并不总是会是右键单击触发上下文菜单事件,但当上下文菜单键被按下时(这可以说是右键单击的替代)

其他回答

如果你正在寻找“更好的Javascript鼠标事件”,其中允许

离开mousedown 中间mousedown 对mousedown 离开mouseup 中间mouseup 对mouseup 左键点击 中间点击 右击 mousewheel起来 mousewheel下来

看看这个跨浏览器的正常javascript触发上述事件,并消除了头痛的工作。只需将其复制并粘贴到脚本头部,或将其包含在文档<head>中的文件中。然后绑定你的事件,参考下面的代码块,它显示了一个jquery的例子捕捉事件和触发函数分配给他们,虽然这与正常的javascript绑定工作以及。

如果您对它的工作感兴趣,可以查看jsFiddle: https://jsfiddle.net/BNefn/

/**
   Better Javascript Mouse Events
   Author: Casey Childers
**/
(function(){
    // use addEvent cross-browser shim: https://gist.github.com/dciccale/5394590/
    var addEvent = function(a,b,c){try{a.addEventListener(b,c,!1)}catch(d){a.attachEvent('on'+b,c)}};

    /* This function detects what mouse button was used, left, right, middle, or middle scroll either direction */
    function GetMouseButton(e) {
        e = window.event || e; // Normalize event variable

        var button = '';
        if (e.type == 'mousedown' || e.type == 'click' || e.type == 'contextmenu' || e.type == 'mouseup') {
            if (e.which == null) {
                button = (e.button < 2) ? "left" : ((e.button == 4) ? "middle" : "right");
            } else {
                button = (e.which < 2) ? "left" : ((e.which == 2) ? "middle" : "right");
            }
        } else {
            var direction = e.detail ? e.detail * (-120) : e.wheelDelta;
            switch (direction) {
                case 120:
                case 240:
                case 360:
                    button = "up";
                break;
                case -120:
                case -240:
                case -360:
                    button = "down";
                break;
            }
        }

        var type = e.type
        if(e.type == 'contextmenu') {type = "click";}
        if(e.type == 'DOMMouseScroll') {type = "mousewheel";}

        switch(button) {
            case 'contextmenu':
            case 'left':
            case 'middle':
            case 'up':
            case 'down':
            case 'right':
                if (document.createEvent) {
                  event = new Event(type+':'+button);
                  e.target.dispatchEvent(event);
                } else {
                  event = document.createEventObject();
                  e.target.fireEvent('on'+type+':'+button, event);
                }
            break;
        }
    }

    addEvent(window, 'mousedown', GetMouseButton);
    addEvent(window, 'mouseup', GetMouseButton);
    addEvent(window, 'click', GetMouseButton);
    addEvent(window, 'contextmenu', GetMouseButton);

    /* One of FireFox's browser versions doesn't recognize mousewheel, we account for that in this line */
    var MouseWheelEvent = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";
    addEvent(window, MouseWheelEvent, GetMouseButton);
})();

更好的鼠标点击事件示例(使用jquery为简单,但以上将跨浏览器工作,并触发相同的事件名称,IE使用在名称之前)

<div id="Test"></div>
<script type="text/javascript">
    $('#Test').on('mouseup',function(e){$(this).append(e.type+'<br />');})
              .on('mouseup:left',function(e){$(this).append(e.type+'<br />');})
              .on('mouseup:middle',function(e){$(this).append(e.type+'<br />');})
              .on('mouseup:right',function(e){$(this).append(e.type+'<br />');})

              .on('click',function(e){$(this).append(e.type+'<br />');})
              .on('click:left',function(e){$(this).append(e.type+'<br />');})
              .on('click:middle',function(e){$(this).append(e.type+'<br />');})
              .on('click:right',function(e){$(this).append(e.type+'<br />');})

              .on('mousedown',function(e){$(this).html('').append(e.type+'<br />');})
              .on('mousedown:left',function(e){$(this).append(e.type+'<br />');})
              .on('mousedown:middle',function(e){$(this).append(e.type+'<br />');})
              .on('mousedown:right',function(e){$(this).append(e.type+'<br />');})

              .on('mousewheel',function(e){$(this).append(e.type+'<br />');})
              .on('mousewheel:up',function(e){$(this).append(e.type+'<br />');})
              .on('mousewheel:down',function(e){$(this).append(e.type+'<br />');})
              ;
</script>

对于那些需要缩小版的人…

!function(){function e(e){e=window.event||e;var t="";if("mousedown"==e.type||"click"==e.type||"contextmenu"==e.type||"mouseup"==e.type)t=null==e.which?e.button<2?"left":4==e.button?"middle":"right":e.which<2?"left":2==e.which?"middle":"right";else{var n=e.detail?-120*e.detail:e.wheelDelta;switch(n){case 120:case 240:case 360:t="up";break;case-120:case-240:case-360:t="down"}}var c=e.type;switch("contextmenu"==e.type&&(c="click"),"DOMMouseScroll"==e.type&&(c="mousewheel"),t){case"contextmenu":case"left":case"middle":case"up":case"down":case"right":document.createEvent?(event=new Event(c+":"+t),e.target.dispatchEvent(event)):(event=document.createEventObject(),e.target.fireEvent("on"+c+":"+t,event))}}var t=function(e,t,n){try{e.addEventListener(t,n,!1)}catch(c){e.attachEvent("on"+t,n)}};t(window,"mousedown",e),t(window,"mouseup",e),t(window,"click",e),t(window,"contextmenu",e);var n=/Firefox/i.test(navigator.userAgent)?"DOMMouseScroll":"mousewheel";t(window,n,e)}();

从jQuery 1.1.3版本开始,事件。使事件正常化。keyCode和事件。charCode,这样就不必担心浏览器兼容性问题。关于event.which的文档

事件。它将分别给1、2或3个鼠标左、中、右按钮,这样:

$('#element').mousedown(function(event) {
    switch (event.which) {
        case 1:
            alert('Left Mouse button pressed.');
            break;
        case 2:
            alert('Middle Mouse button pressed.');
            break;
        case 3:
            alert('Right Mouse button pressed.');
            break;
        default:
            alert('You have a strange Mouse!');
    }
});

老旧的帖子,但想分享完整的答案,人们问上面所有的鼠标点击事件类型。

添加这个脚本,使它适用于整个页面:

var onMousedown = function (e) {
     if (e.which === 1) {/* Left Mouse Click */}
     else if (e.which === 2) {/* Middle Mouse Click */}
     else if (e.which === 3) {/* Right Mouse Click */}
};
clickArea.addEventListener("mousedown", onMousedown);

注意:确保你在被点击的元素上'返回false;' -这真的很重要。

干杯!

<!DOCTYPE html>
<html>
<head>
    <title>JS Mouse Events - Button Demo</title>
</head>
<body>
    <button id="btn">Click me with any mouse button: left, right, middle, ...</button>
    <p id="message"></p>
    <script>
        let btn = document.querySelector('#btn');

        // disable context menu when right-mouse clicked
        btn.addEventListener('contextmenu', (e) => {
            e.preventDefault();
        });

        // show the mouse event message
        btn.addEventListener('mouseup', (e) => {
            let msg = document.querySelector('#message');
            switch (e.button) {
                case 0:
                    msg.textContent = 'Left mouse button clicked.';
                    break;
                case 1:
                    msg.textContent = 'Middle mouse button clicked.';
                    break;
                case 2:
                    msg.textContent = 'Right mouse button clicked.';
                    break;
                default:
                    msg.textContent = `Unknown mouse button code: ${event.button}`;
            }
        });
    </script>
</body>
</html>

你可以试试下面的代码:

event.button

返回值:一个数字,表示鼠标事件发生时按下的鼠标按钮。

可能的值:

0:鼠标左键 1:车轮按钮或中间按钮(如果有) 2:鼠标右键 注意:ie8及更早版本有不同的返回值:

1:鼠标左键 2:鼠标右键 4:滚轮按钮或中间按钮(如果有的话)注意:对于左侧配置的鼠标,返回值颠倒