javascript JS:在没有 jQuery 的情况下检测右键单击(内联)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9500743/
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
JS: detect right click without jQuery (inline)
提问by Keith L.
I'm calling a function, that builds a table which includes several links.
我正在调用一个函数,该函数构建一个包含多个链接的表。
I want to check if a link has been clicked with right or left mouse.
我想检查是否用鼠标右键或左键单击了链接。
I tried to add the following part to the <a>
hyperlink.
我尝试将以下部分添加到<a>
超链接中。
onmousedown="function mouseDown(e){
switch (e.which) {
case 1: alert('left'); break;
case 2: alert('middle'); break;
case 3: alert('right'); break; }
}"
But nothing happens If I click on a link.
但是如果我点击一个链接,什么也不会发生。
回答by xdazz
回答by Sean N.
Here's a modification of xdazz's answer that supports browsers that use e.button, normalizes the value, and stores it in e.which. The added lines are what are used in the JQuery library.
这是对 xdazz 答案的修改,它支持使用 e.button 的浏览器,将值标准化并将其存储在 e.which 中。添加的行是 JQuery 库中使用的行。
function mouseDown(e) {
e = e || window.event;
if ( !e.which && e.button !== undefined ) {
e.which = ( e.button & 1 ? 1 : ( e.button & 2 ? 3 : ( e.button & 4 ? 2 : 0 ) ) );
}
switch (e.which) {
case 1: alert('left'); break;
case 2: alert('middle'); break;
case 3: alert('right'); break;
}
}?