MDN wants to talk to developers like you: https://qsurvey.mozilla.com/s3/8d22564490d8

DataTransfer.setData()

这篇翻译不完整。请帮忙从英语翻译这篇文章

DataTransfer.setData() 方法用来设置拖放操作的drag data数据和数据类型。如果给定的数据类型不存在,这个不合法的数据类型会被当作数据放到真正的数据后面。such that the last item in the types list will be the new type. If data for the given type already exists, the existing data is replaced in the same position. That is, the order of the types list is not changed when replacing data of the same type.

参数data的数据类型有:"text/plain" 和 "text/uri-list".

语法

void dataTransfer.setData(format, data);

参数

format
传递数据 data的类型
A DOMString representing the type of the drag data to add to the drag object.
data
A DOMString representing the data to add to the drag object.

Return value

void

Example

This example shows the use of the DataTransfer object's getData(), setData() and clearData() methods.

<!DOCTYPE html>
<html lang=en>
<title>Examples of DataTransfer.{setData(),getData(),clearData()</title>
<meta content="width=device-width">
<style>
  div {
    margin: 0em;
    padding: 2em;
  }
  #source {
    color: blue;
    border: 1px solid black;
  }
  #target {
    border: 1px solid black;
  }
</style>
<script>
function dragstart_handler(ev) {
 console.log("dragStart");
 // Change the source element's background color to signify drag has started
 ev.currentTarget.style.border = "dashed";
 // Set the drag's format and data. Use the event target's id for the data 
 ev.dataTransfer.setData("text/plain", ev.target.id);
}

function dragover_handler(ev) {
 console.log("dragOver");
 ev.preventDefault();
}

function drop_handler(ev) {
 console.log("Drop");
 ev.preventDefault();
 // Get the data, which is the id of the drop target
 var data = ev.dataTransfer.getData("text");
 ev.target.appendChild(document.getElementById(data));
 // Clear the drag data cache (for all formats/types)
 ev.dataTransfer.clearData();
}
</script>
<body>
<h1>Examples of <code>DataTransfer</code>: <code>setData()</code>, <code>getData()</code>, <code>clearData()</code></h1>
 <div>
   <p id="source" ondragstart="dragstart_handler(event);" draggable="true">
     Select this element, drag it to the Drop Zone and then release the selection to move the element.</p>
 </div>
 <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
</body>
</html>

Specifications

Specification Status Comment
WHATWG HTML Living Standard
setData()
Living Standard  
HTML5.1
setData()
Recommendation Initial definition

Browser compatibility

  
Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 4 (Yes) 3.5 10 12 3.1
  
Feature Android Android Webview Chrome for Android Edge Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile
Basic support 未实现 未实现 未实现 (Yes) 未实现 未实现 10 未实现 未实现

See also

文档标签和贡献者

 此页面的贡献者: imnodb, maicss
 最后编辑者: imnodb,