根据HTML5拖放API上的the documentation,放置元素时会触发两个事件:
drop
事件dragend
事件在进行简单测试(请参见代码段)时,
drop
事件始终在dragend
事件之前触发(至少在Chrome中如此),但我在规范中找不到有关这些事件顺序的任何信息。这些事件的顺序是否已定义,或者可以任意顺序触发?
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
console.log("drop at " + Date.now());
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
function dragend(ev) {
console.log("dragend at " + Date.now());
}
#div1 {
background-color: red;
height: 100px;
width: 100px;
}
#drag1 {
background-color: green;
height: 50px;
width: 50px;
}
<div>Drag the green square in to the red one</div>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)" width="100px" height="100px"></div>
<div id="drag1" draggable="true" ondragstart="drag(event)" ondragend="dragend(event)" width="50px" height="50px">
最佳答案
根据当前(2017年5月8日更新)HTML规范中指定的drag-and-drop processing model,drop()
事件必须在 dragend()
事件之前触发。
相应的信息深深地嵌套在文档中,但是描述拖动操作结束的部分如下所示(省略和重点说明):