[英]disable right click in javascript
When I was trying to disable the right click, it is not working. 当我试图禁用右键单击时,它无法正常工作。 I tried with below code.
我试过下面的代码。
document.onclick = function(e) {
console.log(e.button);
if(e.button == 2){
e.preventDefault();
return false;
}
}
Based on below link only I tried. 基于以下链接,我试过。 Disable Right Click in website
禁用网站右键单击
I tested this code in Chrome and Firefox. 我在Chrome和Firefox中测试了这段代码。 Every time I am getting the right output only in console.
每次我只在控制台中获得正确的输出。 I mean "0" for left click and "2" for right click.But still the default action is happening.
我的意思是左键单击为“0”,右键单击为“2”。但仍然会发生默认操作。 May I know the reason.?
我可以知道原因吗? Thanks in advance.
提前致谢。
You are using wrong event. 您使用的是错误的事件。 For right click you should use
oncontextmenu
. 要右键单击,您应该使用
oncontextmenu
。 You used onclick
which obviously don't fire in right click and hence the loop doesn't evaluate to true in this case. 您使用了
onclick
,这显然不会在右键单击中触发,因此在这种情况下循环不会评估为true。
document.oncontextmenu = function (e) {
console.log(e.button);
if (e.button == 2) {
e.preventDefault();
return false;
}
}
Demo: http://jsfiddle.net/GCu2D/748/ 演示: http : //jsfiddle.net/GCu2D/748/
Only three lines of code can disable right click on a web page that is given below: 只有三行代码可以禁用右键单击下面给出的网页:
$("html").on("contextmenu",function(e){
return false;
});
Source: Close current tab in browser window using JavaScript 来源: 使用JavaScript关闭浏览器窗口中的当前选项卡
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.