我需要在我的页面上放一张图片。我要禁用图像的拖拽。我尝试了很多方法,但都无济于事。有人能帮我一下吗?

我不想保留那个图像作为背景图像因为我在调整图像的大小。


当前回答

为图像设置以下CSS属性:

user-drag: none; 
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;

其他回答

这段代码正是您想要的。它可以阻止图像拖动,同时允许依赖于该事件的任何其他操作。

$("img").mousedown(function(e){
    e.preventDefault()
});

CSS唯一的解决方案:使用指针事件:none

https://developer.mozilla.org/en-US/docs/CSS/pointer-events

最简单的跨浏览器解决方案是

<img draggable="false" ondragstart="return false;" src="..." />

问题

img {
 -moz-user-select: none;
 -webkit-user-select: none;
 -ms-user-select: none;
 user-select: none;
 -webkit-user-drag: none;
 user-drag: none;
 -webkit-touch-callout: none;
}

是它不能在firefox中工作吗

好吧,这是可能的,其他的答案是完全有效的,但你可以采取暴力的方法,防止鼠标在图像上的默认行为。也就是开始拖动图像。

就像这样:

window.onload = function () {  
    var images = document.getElementsByTagName('img');   
    for (var i = 0; img = images[i++];) {    
        img.ondragstart = function() { return false; };
    }  
};  

看看这个答案;在Chrome和Safari中,你可以使用以下样式禁用默认拖拽:

-webkit-user-drag: auto | element | none;

您可以尝试用户选择Firefox和IE(10+):

-moz-user-select: none | text | all | element
-ms-user-select: none | text | all | element