disable right click in javascript

大城市里の小女人 提交于 2019-12-10 15:55:58

问题


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. 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.


回答1:


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;
    }

}

Demo: http://jsfiddle.net/GCu2D/748/




回答2:


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



来源:https://stackoverflow.com/questions/30965212/disable-right-click-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!