我想知道如何使用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>
这个可行:
$('img').bind('contextmenu', function(e) {
return false;
});
或者对于更新的jQuery:
$('#nearestStaticContainer').on('contextmenu', 'img', function(e){
return false;
});
$('body').on('contextmenu', 'img', function(e){ return false; });
不过如果可以的话,我建议使用比 'body'
更精确的选择器。 - Myster禁用右键的目的是什么?任何技术都有被绕过的方法。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>
在Chrome和Firefox中,如果我使用'bind'方法,上述方法不起作用,除非我改为使用'live'。
以下内容对我有效:
$('img').live('contextmenu', function(e){
return false;
});
现代浏览器只需要以下CSS即可:
img {
pointer-events: none;
}
旧版浏览器仍然允许在图像上进行指针事件,但是上面的CSS将照顾到您网站的绝大部分访问者,并且与contextmenu
方法一起使用应该会为您提供非常可靠的解决方案。
没有使用jQuery更好的方法:
const images = document.getElementsByTagName('img');
for (let i = 0; i < images.length; i++) {
images[i].addEventListener('contextmenu', event => event.preventDefault());
}
当一个单独的水印被放置在图片上时,是否可以仍然保留右键点击并下载的功能。当然这并不能防止截屏,但认为这可能是一个好的折衷方案。
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;
});
});