<!DOCTYPE html>
<html>
<head>
<meta charset=
"UTF-8"
>
<title>Drag & Drop</title>
<style type=
"text/css"
>
.box {
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid #ccccff;
background-color: #ccccff;
text-align: center;
line-height: 100px;
}
.bin {
width: 200px;
height: 200px;
padding: 10px;
border: 1px solid #ccccff;
overflow: hidden;
float: left;
}
</style>
</head>
<body>
<p style=
"display: table;"
>
<p
class
=
"bin"
>
<p
class
=
"box"
draggable=
"true"
>可拖拽元素</p>
</p>
<p
class
=
"bin"
> </p>
</p>
<script type=
"text/javascript"
>
var
bins = document.querySelectorAll(
'.bin'
);
var
boxs = document.querySelectorAll(
'.box'
);
var
drag = null;
for
(
var
i = 0; i < boxs.length; i++) {
var
box = boxs[i];
box.onselectstart =
function
() {
return
false;
};
box.ondragstart =
function
(e) {
e.dataTransfer.effectAllowed =
'move'
;
e.dataTransfer.setData(
'text/plain'
, e.target.outerHTML);
e.dataTransfer.setDragImage(e.target, 0, 0);
drag = this;
return
true;
};
box.ondragend =
function
(e) {
drag = null;
return
false
};
}
for
(
var
i = 0; i < bins.length; i++) {
var
bin = bins[i];
bin.ondragover =
function
(e) {
e.preentDefault();
return
true;
};
bin.ondragenter =
function
(e) {
this.style.backgroundColor =
'#eeeeff'
;
return
true;
};
bin.ondragleave =
function
(e) {
this.style.backgroundColor =
'#fff'
;
return
true;
};
bin.ondrop =
function
(e) {
if
(drag) {
drag.parentNode.removeChild(drag);
this.appendChild(drag);
}
this.style.backgroundColor =
'#fff'
;
return
false;
};
}
document.body.ondrop =
function
(e) {
e.preventDefault();
e.stopPropagation();
}
</script>
</body>
</html>