DataTransfer.getData()

DataTransfer.getData() 方法接受指定类型的拖放(以DOMString的形式)数据。如果拖放行为没有操作任何数据,会返回一个空字符串。

数据类型有:text/plaintext/uri-list。

语法

DOMString dataTransfer.getData(format);

参数

format
DOMString类型

返回值

DOMString
返回一个给定类型的DOMString格式的数据。如果没有操作数据或者没有指定操作数据的类型,都会返回一个空字符串。

注意

HTML5 拖放规范 规定了一个 drag data store mode。这可能会导致预期外的结果,即 DataTransfer.getData() 没有返回预期值。

示例

这个例子展示了 DataTransfer对象的getData()setData()方法。

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

#div1, #div2 {
    width:100px;
    height:50px;
    padding:10px;
    border:1px solid #aaaaaa;
}

JavaScript

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 Status Comment
HTML Living Standard
getData()
Living Standard
HTML 5.1
getData()
Recommendation Initial definition

兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
getDataChrome Full support YesEdge Full support 12Firefox Full support YesIE ? Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS No support NoSamsung Internet Android Full support Yes

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown

参考