2015-06-21 88 views
4

当我试图禁用右键单击时,它不起作用。 我试着用下面的代码。在javascript中禁用右键单击

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

根据以下链接我试过了。 Disable Right Click in website

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

回答

6

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

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

} 

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