DataTransfer: items 属性
值
一个包含 DataTransferItem
对象的 DataTransferItemList
对象,表示拖放操作中被拖动的项目,每个被拖动的对象对应一个列表项。如果拖放操作没有数据,则列表为空。
示例
记录拖动的项目
此示例使用 items
记录有关拖动项目的的信息。
HTML
html
<ul>
<li id="source1" draggable="true">Drag Item 1 to the Drop Zone</li>
<li id="source2" draggable="true">Drag Item 2 to the Drop Zone</li>
</ul>
<div id="target">Drop Zone</div>
<button id="reset">Reset</button>
CSS
css
div {
margin: 0em;
padding: 2em;
}
#target {
border: 1px solid black;
}
JavaScript
js
function dragstartHandler(ev) {
console.log(`dragstart: target.id = ${ev.target.id}`);
// Add this element's id to the drag payload so the drop handler will
// know which element to add to its tree
ev.dataTransfer.setData("text/plain", ev.target.id);
ev.dataTransfer.effectAllowed = "move";
}
function dropHandler(ev) {
ev.preventDefault();
// Get the id of the target and add the moved element to the target's DOM
const data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
// Print each item's "kind" and "type"
if (ev.dataTransfer.items) {
for (const item of ev.dataTransfer.items) {
console.log(`kind = ${item.kind}, type = ${item.type}`);
}
}
}
function dragoverHandler(ev) {
ev.preventDefault();
// Set the dropEffect to move
ev.dataTransfer.dropEffect = "move";
}
const source1 = document.querySelector("#source1");
const source2 = document.querySelector("#source2");
const target = document.querySelector("#target");
source1.addEventListener("dragstart", dragstartHandler);
source2.addEventListener("dragstart", dragstartHandler);
target.addEventListener("dragover", dragoverHandler);
target.addEventListener("drop", dropHandler);
const reset = document.querySelector("#reset");
reset.addEventListener("click", () => document.location.reload());
结果
规范
规范 |
---|
HTML 标准 # dom-datatransfer-items-dev |
浏览器兼容性
BCD 表格仅在启用了 JavaScript 的浏览器中加载。