我想知道如何使用jQuery禁用对图像的右键单击。
我只知道这一点:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(document).bind("contextmenu",function(e) {
return false;
});
});
</script>
我想知道如何使用jQuery禁用对图像的右键单击。
我只知道这一点:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(document).bind("contextmenu",function(e) {
return false;
});
});
</script>
Answers:
这有效:
$('img').bind('contextmenu', function(e) {
return false;
});
或对于较新的jQuery:
$('#nearestStaticContainer').on('contextmenu', 'img', function(e){
return false;
});
$('body').on('contextmenu', 'img', function(e){ return false; }); 尽管我会建议比“身体”窄的东西。
禁用右键单击的目的是什么。任何技术的问题都是总有办法解决它们。Firefox(firebug)和chrome控制台允许取消绑定该事件。或者,如果您想保护图像,可以总是只看一下图像的临时缓存。
如果要创建自己的上下文菜单,则preventDefault可以。只需在这里挑选您的战斗。甚至没有像tnyMCE这样的大JavaScript库在所有浏览器上都可以运行...这不是因为不可能;-)。
$(document).bind("contextmenu",function(e){
e.preventDefault()
});
就个人而言,我更喜欢开放的互联网。页面交互不应妨碍本机浏览器的行为。我确信可以找到其他方法,而不是右键单击。
对于禁用右键单击选项
<script type="text/javascript">
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>
您可以尝试这样:
var message="Sorry, right-click has been disabled";
function clickIE() {
if (document.all) {
(message);
return false;
}
}
function clickNS(e) {
if (document.layers || (document.getElementById && !document.all)) {
if (e.which == 2||e.which == 3) {
(message);
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = clickNS;
} else {
document.onmouseup = clickNS;
document.oncontextmenu = clickIE;
}
document.oncontextmenu = new Function("return false")
这应该工作
$(function(){
$('body').on('contextmenu', 'img', function(e){
return false;
});
});
没有jQuery的更好方法是:
const images = document.getElementsByTagName('img');
for (let i = 0; i < images.length; i++) {
images[i].addEventListener('contextmenu', event => event.preventDefault());
}