根据 the documentation在 HTML5 拖放 API 上,当元素被放下时会触发两个事件:
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">
最佳答案
根据drag-and-drop processing model在当前(2021 年 6 月 8 日更新)HTML 规范中指定,drop()
事件必须在 dragend()
事件之前触发。
相应的信息嵌套在文档中很深,但是描述拖动操作结束的部分看起来如下(我的省略和强调):
Otherwise, if the user ended the drag-and-drop operation (e.g. by releasing the mouse button in a mouse-driven drag-and-drop interface), or if the
drag
event was canceled, then this will be the last iteration. Run the following steps, then stop the drag-and-drop operation:
- [...]
Otherwise, the drag operation might be a success; run these substeps:
- Let dropped be true.
- If the current target element is a DOM element, fire a DND event named
drop
at it; otherwise, use platform-specific conventions for indicating a drop.- [...]
- Fire a DND event named
dragend
at the source node.- [...]
关于javascript - dragend 和 drop 事件之间是否有定义的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111946/