如何在禁用浏览器上下文菜单后通过右键单击触发某些操作?
我尝试了这个...
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
$('.alert').fadeToggle();
return false;
});
});
jQuery中没有内置的oncontextmenu事件处理程序,但您可以像这样操作:
$(document).ready(function(){
document.oncontextmenu = function() {return false;};
$(document).mousedown(function(e){
if( e.button == 2 ) {
alert('Right mouse button!');
return false;
}
return true;
});
});
我基本上取消了DOM元素的oncontextmenu事件以禁用浏览器上下文菜单,然后使用jQuery捕获mousedown事件,在事件参数中你可以知道按下了哪个按钮。
你可以在这里尝试上述示例。
$(document)[0]
不就是 document
吗? - configuratore.button
的数值是特定于浏览器或硬件的。 - B T这个函数返回得太早了。我在下面的代码中添加了一条注释:
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
$('.alert').fadeToggle(); // this line never gets called
});
});
尝试将return false;
与下一行交换。$('.js-my-element').bind('contextmenu', function(e) {
e.preventDefault();
alert('The eventhandler will make sure, that the contextmenu dosn't appear.');
});
$.fn.customContextMenu = function(callBack){
$(this).each(function(){
$(this).bind("contextmenu",function(e){
e.preventDefault();
callBack();
});
});
}
以下是我的页面脚本中的代码:
$("#newmagazine").customContextMenu(function(){
alert("some code");
});
.contextmenu 方法:
请尝试以下操作:
<div id="wrap">Right click</div>
<script>
$('#wrap').contextmenu(function() {
alert("Right click");
});
</script>
.mousedown 方法:
$('#wrap').mousedown(function(event) {
if(event.which == 3){
alert('Right Mouse button pressed.');
}
});
document.oncontextmenu = function() {return false;}; //disable the browser context menu
$('selector-name')[0].oncontextmenu = function(){} //set jquery element context menu
document.oncontextmenu = function() {return false;};
完全不起作用。在浏览器(Chrome 66)中仍然会出现上下文菜单。 - basZero要禁用网页上所有图像的右键菜单,只需按照以下方式进行:
jQuery(document).ready(function(){
// Disable context menu on images by right clicking
for(i=0;i<document.images.length;i++) {
document.images[i].onmousedown = protect;
}
});
function protect (e) {
//alert('Right mouse button not allowed!');
this.oncontextmenu = function() {return false;};
}
contextmenu
是一个事件吗?
我会使用 onmousedown
或者 onclick
, 然后获取 MouseEvent
的 button 属性来确定哪个按钮被按下 (0 = 左键, 1 = 中间键, 2 = 右键)。