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

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

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

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

当前回答

$.event.special.rightclick = {
    bindType: "contextmenu",
    delegateType: "contextmenu"
};

$(document).on("rightclick", "div", function() {
    console.log("hello");
    return false;
});

http://jsfiddle.net/SRX3y/8/

其他回答

    $.event.special.rightclick = {
     bindType: "contextmenu",
        delegateType: "contextmenu"
      };

   $(document).on("rightclick", "div", function() {
   console.log("hello");
    return false;
    });

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

对于那些不知道是否应该使用事件的人。在普通JS或Angular中:现在已弃用,所以更喜欢使用event。按钮。

注意:使用此方法和(mousedown)事件:

左键按关联到1 右键单击与2关联 滚动按钮按下与4相关联

and (mouseup)事件将不会返回相同的数字,而是0。

来源:https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons

通过查看鼠标事件的事件对象的属性,你可以很容易地知道按下了哪个鼠标按钮:

/*
  1 = Left   mouse button
  2 = Centre mouse button
  3 = Right  mouse button
*/

$([selector]).mousedown(function(e) {
    if (e.which === 3) {
        /* Right mouse button was clicked! */
    }
});
$(document).ready(function () {
    var resizing = false;
    var frame = $("#frame");
    var origHeightFrame = frame.height();
    var origwidthFrame = frame.width();
    var origPosYGrip = $("#frame-grip").offset().top;
    var origPosXGrip = $("#frame-grip").offset().left;
    var gripHeight = $("#frame-grip").height();
    var gripWidth = $("#frame-grip").width();

    $("#frame-grip").mouseup(function (e) {
        resizing = false;
    });

    $("#frame-grip").mousedown(function (e) {
        resizing = true;
    });
    document.onmousemove = getMousepoints;
    var mousex = 0, mousey = 0, scrollTop = 0, scrollLeft = 0;
    function getMousepoints() {
        if (resizing) {
            var MouseBtnClick = event.which;
            if (MouseBtnClick == 1) {
                scrollTop = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;
                scrollLeft = document.documentElement ? document.documentElement.scrollLeft : document.body.scrollLeft;
                mousex = event.clientX + scrollLeft;
                mousey = event.clientY + scrollTop;

                frame.height(mousey);
                frame.width(mousex);
            }
            else {
                resizing = false;
            }
        }
        return true;

    }


});