HTML文件
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#div{
514px;
height: 345px;
margin: 0 auto;
border: 4px solid #aaa;
padding: 20px;
}
img{
padding: 1px;
border: 1px solid #4A4D4A;
}
</style>
</head>
<body>
<div id="div"></div>
<br><br><br>
<img src="img/4.jpg" id="img4">
<img src="img/5.jpg" id="img5">
<img src="img/6.jpg" id="img6">
<img src="img/7.jpg" id="img7">
<script type="text/javascript">
//获取所有的img
var img = document.getElementsByTagName('img');
for(var i = 0; i < img.length; i++){
img[i].ondragstart = function(){
//拖拽数据传递对象
event.dataTransfer.setData('text',event.target.id);
}
}
//获取div
var div = document.getElementById('div');
//取消浏览器的拖拽效果
div.ondragover = function(){
event.preventDefault();
}
//拖拽
div.ondrop = function(){
//接受发送过来的img ID
var id = event.dataTransfer.getData('text');
var img = document.getElementById(id);
//添加子节点
div.appendChild(img);
}
</script>
</body>
</html>
效果预览: