如何在 JavaScript 中捕获右键单击事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4235426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I capture the right-click event in JavaScript?
提问by Giffyguy
I want to block the standard context menus, and handle the right-click event manually.
我想阻止标准上下文菜单,并手动处理右键单击事件。
How is this done?
这是怎么做的?
回答by Chase
Use the oncontextmenu
event.
使用oncontextmenu
事件。
Here's an example:
下面是一个例子:
<div oncontextmenu="javascript:alert('success!');return false;">
Lorem Ipsum
</div>
And using event listeners:
并使用事件侦听器:
el.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success!');
return false;
}, false);
Don't forget to return false, otherwise the standard context menu will still pop up.
不要忘记返回false,否则仍然会弹出标准上下文菜单。
If you are going to use a function you've written rather than javascript:alert("Success!")
, remember to return false in BOTH the function AND the oncontextmenu
attribute.
如果要使用自己编写的函数而不是javascript:alert("Success!")
,请记住在函数和oncontextmenu
属性中都返回 false 。
回答by cyber-guard
I think that you are looking for something like this:
我认为你正在寻找这样的东西:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
( http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
然后即使使用函数 rightclick() 使用 onmousedown (如果你想在整个页面上全局使用它,你可以这样做 <body onmousedown=rightclick(); >