DataTransferItem: getAsString() 方法

Baseline 已廣泛支援

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

如果拖拽資料項的 kind 是*純 unicode 字串*(即 kindstring),則 DataTransferItem.getAsString() 方法會呼叫給定的回撥函式,並將該資料項的字串資料作為引數。

語法

js
getAsString(callbackFn)

引數

callbackFn

一個接收以下引數的回撥函式

data

DataTransferItem 的字串資料。

返回值

無(undefined)。

示例

此示例展示了在 drop 事件處理程式中將 getAsString() 方法用作*行內函數*。

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-getasstring-dev

瀏覽器相容性

另見