是否有一种方法可以防止用户看到他们试图拖动的图像的幽灵(不是关心图像的安全性,而是体验)。

我已经尝试了这个,它修复了文本和图像上的蓝色选择的问题,但不是幽灵图像:

img {
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  user-select: none;
}

(我也尝试用同样的规则嵌套div内的图像)。 谢谢


当前回答

HTML

<img draggable="false" src="img/example.jpg">

JavaScript

document.querySelector('img').addEventListener('dragstart', (event) => {
  event.preventDefault();
});

CSS

img {
  -webkit-user-drag: none;
}

目前在浏览器或标准轨道中没有无前缀的user-drag或其他版本的属性实现,因为HTML可拖动属性/属性是首选的解决方案。

它是webkit特有的属性。以下是WebKit文档对它的描述:

Heading WebKit provides automatic support to let users drag common items, such as images, links, and selected text. You can extend this support to include specific elements on an HTML page. For example, you could mark a particular div or span tag as draggable. To mark an arbitrary element as draggable, add the -webkit-user-drag attribute to the style definition of the element. Because -webkit-user-drag is a cascading style sheet (CSS) attribute, you can include it as part of a style definition, or as an inline style attribute on the element tag. The values for this attribute are listed in Table 4-1. Values for -webkit-user-drag attribute: none: Do not allow this element to be dragged. element: Allow this element to be dragged. auto: Use the default logic for determining whether the element should be dragged. (Images, links, and text selections are the only elements that can be dragged.) This is the default value.

所有使用WebKit渲染引擎的浏览器都支持它,比如Chrome、更新版本的Opera、Safari等等。使用WebKit的移动浏览器的支持可能因移动操作系统而异。

其他回答

我发现,对于IE,你必须添加draggable="false"属性的图像和锚,以防止拖动。CSS选项适用于所有其他浏览器。我用jQuery做了这个:

$("a").attr('draggable', false); 
$("img").attr('draggable', false);

在Firefox上测试:删除和放回图像工作!而且在执行过程中也是透明的。例如,

$('.imageContainerClass').mousedown(function() {
    var id = $(this).attr('id');
    $('#'+id).remove();
    $('#'+id).append('Image tag code');
});

编辑:奇怪的是,这只适用于IE和Firefox。我还在每张图片上添加了draggable = false。Chrome和Safari浏览器仍然是个幽灵。

编辑2:背景图像的解决方案确实是最好的。唯一的微妙之处在于,每当背景图像被改变时,background-size属性都必须重新定义!从我的角度看是这样的。更好的是,我在IE下的普通img标签有一个问题,IE无法调整图像的大小。现在,图像有了正确的尺寸。简单:

$(id).css( 'background-image', url('blah.png') );
$(id).css( 'background-size', '40px');

此外,或许可以考虑以下因素:

background-Repeat:no-repeat;
background-Position: center center;

试一试:

img {
  pointer-events: none;
}

尽量避免

* {
  pointer-events: none;
}

这将在所有浏览器中禁用拖拽图像,同时保留其他事件,如单击和悬停。只要HTML5、JS或CSS可用,就可以使用。

<img draggable="false" onmousedown="return false" style="user-drag: none" />

如果你确信用户将拥有JS,你只需要使用JS属性,等等。要获得更大的灵活性,请查看ondragstart, onselectstart和一些WebKit点击/触摸CSS。

我想你可以改变你的

img {
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  user-select: none;
}

成一个

img {
  -webkit-user-drag: none;
  -khtml-user-drag: none;
  -moz-user-drag: none;
  -o-user-drag: none;
  user-drag: none;
}