直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#dragTarget {
width: 300px;
height: 200px;
background-color: #CCC;
}
</style>
</head>
<body>
<div id="dragTarget"></div>
</body>
<script>
var dragTarget = document.querySelector('#dragTarget')
dragTarget.addEventListener("dragenter", function (ev) {
// 阻止浏览器默认事件
ev.preventDefault();
}, false);
dragTarget.addEventListener("dragover", function (ev) {
// 阻止浏览器默认事件
ev.preventDefault();
}, false);
dragTarget.addEventListener("drop", function (ev) {
ev.preventDefault();
var data = ev.dataTransfer.items;
for (var i = 0; i < data.length; i += 1) {
if ((data[i].kind == 'string') &&
(data[i].type.match('^text/plain'))) {
// This item is the target node
data[i].getAsString(function (s) {
ev.target.appendChild(document.getElementById(s));
});
} else if ((data[i].kind == 'string') &&
(data[i].type.match('^text/html'))) {
// Drag data item is HTML
console.log("... Drop: HTML");
} else if ((data[i].kind == 'string') &&
(data[i].type.match('^text/uri-list'))) {
// Drag data item is URI
console.log("... Drop: URI");
} else if ((data[i].kind == 'file') &&
(data[i].type.match('^image/'))) {
// Drag data item is an image file
var f = data[i].getAsFile();
console.log("... Drop: File ");
}
}
}, false);
</script>
</html>
网友评论