jQuery: preventDefault() not working on input/click events?

隐身守侯 提交于 2019-12-05 03:39:37

A cross-browser solution to disable the default context menu:

window.oncontextmenu = function() { return false };

To capture the contextmenu event only inside a given element use:

document.getElementById('myElement').oncontextmenu=function(){

    // Code to handle event
    return false;
}

You will get different results depending on the exact event scenario and browser if you try methods other than oncontextmenu for interrupting a right-click event.

In jQuery:

$('myElement').bind('contextmenu', function(){

    // Handle right-click event.
    return false;
});

You can also use jQuery's event.which to determine which button was pressed, but you will still have to cancel the default contextmenu event:

   // Cancel default oncontextmenu event.
    $(element).bind('contextmenu', function(){ return false });

    $(element).mousedown(function(event){

        switch (event.which)

            case 1:
            // Left mouse
            break;

            case 2:
            // Middle mouse
            break;

            case 3:
            // Right mouse.
            break;

    });

I've tested this in IE6 (under Wine), Chrome 11, Firefox 3.6, Opera 11 and Safari.

Sorry guys, I know this is a cop-out "answer" because I was never able to figure out exactly why webkit browsers don't like you messing with input field events but whatever, this works. So the solution is to apply the listener to the whole window and then just ask if the target has the class you want to apply the effect to...and go from there. To be honest, this is probably a better solution anyway because for my particular application, this allows me to apply this functionality to any element I want.

var _class = "input.hideRightClick";

this.setListeners = function() {
    $(window).click(function(e) {
        if($(e.target).is(_class))
        {
            e.preventDefault(); 
            alert("hide!");
        }
    });
}

I just tested in Firefox 3.6 and it's proceeding into the first if statement, so the e.preventDefault() is never called.

  var webKit = !$.browser.msie && e.button == 0; // TRUE IN FIREFOX 3.6

  var ie = $.browser.msie && e.button == 1;

  if(webKit||ie)
  { 

   // Left mouse...do something()

  } else if(e.button == 2) {
   e.preventDefault(); 

   // Right mouse...do something else();
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!