当我单击div中的图像并尝试拖动时,只拖动图像而不是整个div。当我将其放入新div时会产生内存不足的异常
HTML:
<div class="box" draggable="true">
<img src="drag icon.png" width="16" height="16"/>
<header>B</header>
<p>
Put me
</p>
</div>
<div class="box" draggable="true">
<img src="drag icon.png" width="16" height="16"/>
<header>C</header>
<p>
right
</p>
</div>
<div class="box" draggable="true">
<img src="drag icon.png" width="16" height="16"/>
<header>D</header>
<p>
into
</p>
</div>
<div class="box" draggable="true">
<img src="drag icon.png" width="16" height="16"/>
<header>E</header>
<p>
the
</p>
</div>
脚本:
(function () {
var id_ = 'boxes-example';
var boxes_ = document.querySelectorAll('#' + id_ + ' .box');
var dragSrcEl_ = null;
this.handleDragStart = function (e) {
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
dragSrcEl_ = this;
this.style.opacity = '0.5';
// this/e.target is the source node.
this.addClassName('moving');
};
this.handleDragOver = function (e) {
if (e.preventDefault) {
e.preventDefault(); // Allows us to drop.
}
e.dataTransfer.dropEffect = 'move';
return false;
};
this.handleDragEnter = function (e) {
this.addClassName('over');
};
this.handleDragLeave = function (e) {
// this/e.target is previous target element.
this.removeClassName('over');
};
this.handleDrop = function (e) {
// this/e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
// Don't do anything if we're dropping on the same box we're dragging.
if (dragSrcEl_ != this) {
dragSrcEl_.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData('text/html');
}
return false;
};
this.handleDragEnd = function (e) {
// this/e.target is the source node.
this.style.opacity = '1';
[ ].forEach.call(boxes_, function (box) {
box.removeClassName('over');
box.removeClassName('moving');
});
};
[ ].forEach.call(boxes_, function (box) {
box.setAttribute('draggable', 'true'); // Enable boxes to be draggable.
box.addEventListener('dragstart', this.handleDragStart, false);
box.addEventListener('dragenter', this.handleDragEnter, false);
box.addEventListener('dragover', this.handleDragOver, false);
box.addEventListener('dragleave', this.handleDragLeave, false);
box.addEventListener('drop', this.handleDrop, false);
box.addEventListener('dragend', this.handleDragEnd, false);
});
})();
这是一个示例基本的html5拖放代码。您可以使用任何拖放代码并检查此问题
答案 0 :(得分:0)
默认情况下,Image可以拖动,并且似乎优先于其父拖动。它通过显式将img draggable设置为false
在FireFox上为我工作<img src="drag icon.png" draggable="false" width="16" height="16"/>
在this fiddle中,我将第一张图片设置为可拖动以显示差异。如果第一个被拖动(B),则拖动整个div,对于其他div,仅拖动图像。 (没有看到拖动事件中的其他行为,纯粹是拖动整个div)
编辑:一种更通用的方法,用于禁用所有图像的拖动:
[].forEach.call(document.querySelectorAll('img') ,function(img){
img.draggable=false;
});