我可以禁用右击在我的网页不使用JavaScript?我问这个问题是因为大多数浏览器允许用户禁用JavaScript。

如果不是,我如何使用JavaScript禁用右键?


当前回答

是的,你可以使用HTML和Javascript禁用它。 只需在你的body或元素上添加oncontextmenu="return false;" 它非常简单,只是使用有效的HTML和Javascript,没有jQuery。

其他回答

如果你只是想禁用右键保存网页上的图像,请使用以下CSS解决方案:

your-img-tag {
  pointer-events: none;
}

在同一映像上实现之前:

在同一映像上实现后:

在Chrome和Firefox中都进行了测试。

 $(document).ready(function () {
            document.oncontextmenu = document.body.oncontextmenu = function () { return false; }
        });

最初的问题是关于如何在用户可以禁用JavaScript的情况下停止右击:这听起来邪恶而邪恶(因此有负面的回答)——但所有的副本都重定向到这里,即使许多副本的目的不那么邪恶。

例如,在HTML5游戏中使用右键按钮。这可以用上面的内联代码来实现,或者像这样更好一点:

document.addEventListener("contextmenu", function (e){
    e.preventDefault();
}, false);

但如果你正在制作一个游戏,那么请记住,右键按钮会触发上下文菜单事件——但它也会触发常规的鼠标下拉和鼠标上拉事件。因此,您需要检查事件的which属性,以确定触发事件的是左(which === 1)、中(which == 2)或右(which === 3)鼠标按钮。

下面是jQuery的一个例子——注意,按下鼠标右键将触发三个事件:鼠标按下事件、上下文菜单事件和鼠标起事件。

// With jQuery
$(document).on({
    "contextmenu": function (e) {
        console.log("ctx menu button:", e.which); 

        // Stop the context menu
        e.preventDefault();
    },
    "mousedown": function(e) { 
        console.log("normal mouse down:", e.which); 
    },
    "mouseup": function(e) { 
        console.log("normal mouse up:", e.which); 
    }
});

所以如果你在游戏中使用鼠标左右键,你就必须在鼠标处理程序中执行一些条件逻辑。

将此代码放入页面的<head>标记中。

<script type="text/javascript"> 
function disableselect(e){  
return false  
}  

function reEnable(){  
return true  
}  

//if IE4+  
document.onselectstart=new Function ("return false")  
document.oncontextmenu=new Function ("return false")  
//if NS6  
if (window.sidebar){  
document.onmousedown=disableselect  
document.onclick=reEnable  
}
</script>

这将禁用右键点击整个网页,但只有当JavaScript启用。

试试这个

<script language=JavaScript>
//Disable right mouse click Script

var message="Function Disabled!";

function clickIE4(){
if (event.button==2){
alert(message);
return false;
 }
}

function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("alert(message);return false")

</script>