DataTransfer.getData() - Web APIs 编辑
The DataTransfer.getData()
method retrieves drag data (as a DOMString
) for the specified type. If the drag operation does not include data, this method returns an empty string.
Example data types are text/plain
and text/uri-list
.
Syntax
dataTransfer.getData(format);
Arguments
format
- A
DOMString
representing the type of data to retrieve.
Return value
DOMString
- A
DOMString
representing the drag data for the specifiedformat
. If the drag operation has no data or the operation has no data for the specifiedformat
, this method returns an empty string.
Caveats
- Data availability
- The HTML5 Drag and Drop Specification dictates a
drag data store mode
. This may result in unexpected behavior, beingDataTransfer.getData()
not returning an expected value.
Example
This example shows the use of the DataTransfer
object's getData()
and setData()
methods.
HTML Content
<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 Content
#div1, #div2 {
width:100px;
height:50px;
padding:10px;
border:1px solid #aaaaaa;
}
JavaScript Content
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';
}
Result
Specifications
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'getData()' in that specification. | Living Standard | |
HTML 5.1 The definition of 'getData()' in that specification. | Recommendation | Initial definition |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论