在JavaScript中禁用右键单击 [英] disable right click in javascript

查看:93
本文介绍了在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

我在Chrome和Firefox中测试了这段代码。
每次我只在控制台中获得正确的输出。我的意思是左键单击为0,右键单击为2。但仍然会发生默认操作。我可以知道原因吗?
提前致谢。

I tested this code in Chrome and 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. May I know the reason.? Thanks in advance.

推荐答案

您使用的是错误的事件。对于右键单击,您应该使用 oncontextmenu 。您使用了 onclick ,这显然不会在右键单击时触发,因此在这种情况下循环不会评估为true。

You are using wrong event. For right click you should use oncontextmenu. You used onclick which obviously don't fire in right click and hence the loop doesn't evaluate to true in this case.

document.oncontextmenu = function (e) {
    console.log(e.button);
    if (e.button == 2) {
        e.preventDefault();
        return false;
    }

}

演示:http://jsfiddle.net/GCu2D/748/

这篇关于在JavaScript中禁用右键单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆