HTML 元素:拖放事件

当用户拖动元素或文本选择时,drag 事件每隔几百毫秒就会触发一次。

此事件是可取消的,并且可能会冒泡到 DocumentWindow 对象。

语法

在像 addEventListener() 这样的方法中使用事件名称,或设置事件处理程序属性。

js
addEventListener("drag", (event) => {});

ondrag = (event) => {};

事件类型

事件属性

除了下面列出的属性之外,父接口 Event 中的属性也可以使用。

DragEvent.dataTransfer 只读

在拖放交互期间传输的数据。

示例

拖放示例

HTML

html
<div class="dropzone">
  <div id="draggable" draggable="true">This div is draggable</div>
</div>
<div class="dropzone" id="droptarget"></div>

CSS

css
body {
  /* Prevent the user selecting text in the example */
  user-select: none;
}

#draggable {
  text-align: center;
  background: white;
}

.dropzone {
  width: 200px;
  height: 20px;
  background: blueviolet;
  margin: 10px;
  padding: 10px;
}

.dropzone.dragover {
  background-color: purple;
}

.dragging {
  opacity: 0.5;
}

JavaScript

js
let dragged;

/* events fired on the draggable target */
const source = document.getElementById("draggable");
source.addEventListener("drag", (event) => {
  console.log("dragging");
});

source.addEventListener("dragstart", (event) => {
  // store a ref. on the dragged elem
  dragged = event.target;
  // make it half transparent
  event.target.classList.add("dragging");
});

source.addEventListener("dragend", (event) => {
  // reset the transparency
  event.target.classList.remove("dragging");
});

/* events fired on the drop targets */
const target = document.getElementById("droptarget");
target.addEventListener(
  "dragover",
  (event) => {
    // prevent default to allow drop
    event.preventDefault();
  },
  false,
);

target.addEventListener("dragenter", (event) => {
  // highlight potential drop target when the draggable element enters it
  if (event.target.classList.contains("dropzone")) {
    event.target.classList.add("dragover");
  }
});

target.addEventListener("dragleave", (event) => {
  // reset background of potential drop target when the draggable element leaves it
  if (event.target.classList.contains("dropzone")) {
    event.target.classList.remove("dragover");
  }
});

target.addEventListener("drop", (event) => {
  // prevent default action (open as link for some elements)
  event.preventDefault();
  // move dragged element to the selected drop target
  if (event.target.classList.contains("dropzone")) {
    event.target.classList.remove("dragover");
    event.target.appendChild(dragged);
  }
});

结果

规范

规范
HTML 标准
# ix-handler-ondrag
HTML 标准
# event-dnd-drag

浏览器兼容性

BCD 表格仅在启用了 JavaScript 的浏览器中加载。

另请参阅