DataTransfer.getData()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
DataTransfer.getData()
方法接受指定类型的拖放(以DOMString
的形式)数据。如果拖放行为没有操作任何数据,会返回一个空字符串。
数据类型有:text/plain
,text/uri-list
。
语法
DOMString dataTransfer.getData(format);
参数
返回值
注意
HTML5 拖放规范 规定了一个 drag data store mode
。这可能会导致预期外的结果,即 DataTransfer.getData()
没有返回预期值。
示例
这个例子展示了 DataTransfer
对象的getData()
和setData()
方法。
HTML
html
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<span id="drag" draggable="true" ondragstart="drag(event)"
>drag me to the other box</span
>
</div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
CSS
css
#div1,
#div2 {
width: 100px;
height: 50px;
padding: 10px;
border: 1px solid #aaaaaa;
}
JavaScript
js
function allowDrop(allowdropevent) {
allowdropevent.target.style.color = "blue";
allowdropevent.preventDefault();
}
function drag(dragevent) {
dragevent.dataTransfer.setData("text", dragevent.target.id);
dragevent.target.style.color = "green";
}
function drop(dropevent) {
dropevent.preventDefault();
var data = dropevent.dataTransfer.getData("text");
dropevent.target.appendChild(document.getElementById(data));
document.getElementById("drag").style.color = "black";
}
结果
规范
Specification |
---|
HTML Standard # dom-datatransfer-getdata-dev |
浏览器兼容性
BCD tables only load in the browser