效果预览
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fabcdd2467171db8a81550f9d78f4e62.gif)
代码实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>一颗不甘坠落的流星</title>
<style>
#div1,
#div2 {
float: left;
width: 100px;
height: 27px;
margin: 10px;
padding: 24px 0;
text-align: center;
border: 1px solid #aaaaaa;
}
span {
display: inline-block;
width: 50px;
height: 25px;
background-color: greenyellow;
}
</style>
</head>
<body>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<span draggable="true" ondragstart="drag(event)" id="drag1"></span>
</div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</body>
<script type="text/javascript">
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
通过 dataTransfer.getData() 方法获得被拖的数据。该方法将返回在 setData() 方法中设置为相同类型的任何数据
var data = ev.dataTransfer.getData("Text");
var span = document.getElementById(data)
ev.target.appendChild(span);
}
</script>
</html>