문제

I want to handle right click event on a particular div element. After digging through a number of answers in stackoverflow, I came up with this:

 $('#mydiv').mousedown(function(event) {
if ((event.which == 3)&& (event.target.nodeName == 'SPAN')){
     $("#outpdiv").append($(event.target).text().concat(" , "));
     event.preventDefault();
}
 });

As you can see, I am trying to to append the content of span elements inside mydiv to another div element outpdiv. This works fine, but the problem is after right click, the contextmenu is shown. Apparently, event.preventDefault() does not work. How can I get around this problem so that the context menu is not shown after you do the right click?

도움이 되었습니까?

해결책

Try capturing the contextmenu event and calling preventDefault() in that handler:

http://jsfiddle.net/cTp9x/

$('#mydiv').mousedown(function (event) {
    if ((event.which == 3) && (event.target.nodeName == 'SPAN')) {
        $("#outpdiv").append($(event.target).text().concat(" , "));        
    }
});

$(document).on('contextmenu', function(e) {
    e.preventDefault();
});

In response to your comment. If you only want to disable the context menu when you click that particular div, you can bind the handler to it. Switching between jQuery and native event handlers is messy, IMO:

$('#mydiv').on('contextmenu', function(e) {
    e.preventDefault();
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top