DataTransferItem:type 屬性

Baseline 已廣泛支援

此功能已得到良好確立,並在許多裝置和瀏覽器版本中都可使用。自 ⁨2016 年 11 月⁩以來,它已在所有瀏覽器中可用。

只讀的 DataTransferItem.type 屬性返回表示拖動資料項的 DataTransferItem 物件的型別(格式)。type 是一個 Unicode 字串,通常由 MIME 型別給出,儘管 MIME 型別不是必需的。

一些示例型別包括:text/plaintext/html

一個表示拖動資料項型別的字串。

示例

此示例展示了 type 屬性的使用。

js
function dropHandler(ev) {
  console.log("Drop");
  ev.preventDefault();
  for (const item of ev.dataTransfer.items) {
    if (item.kind === "string" && item.type.match("^text/plain")) {
      // This item is the target node
      item.getAsString((s) => {
        ev.target.appendChild(document.getElementById(s));
      });
    } else if (item.kind === "string" && item.type.match("^text/html")) {
      // Drag data item is HTML
      console.log("… Drop: HTML");
    } else if (item.kind === "string" && item.type.match("^text/uri-list")) {
      // Drag data item is URI
      console.log("… Drop: URI");
    } else if (item.kind === "file" && item.type.match("^image/")) {
      // Drag data item is an image file
      const f = item.getAsFile();
      console.log("… Drop: File");
    }
  }
}

規範

規範
HTML
# dom-datatransferitem-type-dev

瀏覽器相容性

另見