javascript - dragend 和 drop 事件之间是否有定义的顺序?

标签 javascript html drag-and-drop

根据 the documentation在 HTML5 拖放 API 上,当元素被放下时会触发两个事件:

  1. drop 事件从放置目标触发
  2. 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:

  1. [...]
    Otherwise, the drag operation might be a success; run these substeps:
    1. Let dropped be true.
    2. 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.
    3. [...]
  2. Fire a DND event named dragend at the source node.
  3. [...]

关于javascript - dragend 和 drop 事件之间是否有定义的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111946/

相关文章:

javascript - Chrome 阻止重定向到扩展页面

html - 将 CSS 文件链接到我硬盘上同一目录中的 HTML 文档 (Windows)

javascript - 使用 jQuery 将新的 div 容器添加到 div 容器 ID

javascript - Internet Explorer 9 中不再触发 ondragstart 事件

javascript - 如何为网站设计搜索框?

javascript - 如何从图书馆创建 promise

html - 打开 html xls 链接到 EXCEL 应用程序(不在 IE 浏览器中)

javascript - 如何设置拖动元素的样式

javascript - 如何从 HTML 外部拖放 iframe?

javascript - 使用 javascript api 在帖子和位置上标记 friend