DataTransfer:types 属性

DataTransfer.types 只读属性返回 items 中存在的可用类型。

数据格式的数组。每个格式都是一个字符串,通常是 MIME 类型,例如 text/plaintext/html。如果拖放操作不包含任何数据,则此列表将为空。如果拖放操作中包含任何文件,则其中一个类型将是字符串 Files

示例

此示例演示了 typesitems 属性的使用。

html
<!doctype html>
<html lang="en">
  <title>Examples of DataTransfer.{types,items} properties</title>
  <meta content="width=device-width" />
  <style>
    div {
      margin: 0em;
      padding: 2em;
    }
    #target {
      border: 1px solid black;
    }
  </style>
  <script>
    function dragstart_handler(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 drop_handler(ev) {
      console.log("drop: target.id = " + ev.target.id);
      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 format type
      for (let i = 0; i < ev.dataTransfer.types.length; i++) {
        console.log(`… types[${i}] = ${ev.dataTransfer.types[i]}`);
      }

      // Print each item's "kind" and "type"
      for (let i = 0; i < ev.dataTransfer.items.length; i++) {
        console.log(
          `… items[${i}].kind = ${ev.dataTransfer.items[i].kind}; type = ${ev.dataTransfer.items[i].type}`,
        );
      }
    }

    function dragover_handler(ev) {
      console.log("dragOver");
      ev.preventDefault();
      // Set the dropEffect to move
      ev.dataTransfer.dropEffect = "move";
    }
  </script>
  <body>
    <h1>
      Examples of <code>DataTransfer</code>.{<code>types</code>,
      <code>items</code>} properties
    </h1>
    <ul>
      <li id="i1" ondragstart="dragstart_handler(event);" draggable="true">
        Drag Item 1 to the Drop Zone
      </li>
      <li id="i2" ondragstart="dragstart_handler(event);" draggable="true">
        Drag Item 2 to the Drop Zone
      </li>
    </ul>
    <div
      id="target"
      ondrop="drop_handler(event);"
      ondragover="dragover_handler(event);">
      Drop Zone
    </div>
  </body>
</html>

规范

规范
HTML 标准
# dom-datatransfer-types-dev

浏览器兼容性

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

另请参见