<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
width: 1200px;
height: 300px;
margin: 0 auto;
}
.droppable {
display: inline-block;
height: 160px;
width: 160px;
margin: 10px;
border: 3px black solid;
background-color: white;
}
.draggable {
background-image: url('http://source.unsplash.com/random/150x150');
position: relative;
height: 150px;
width: 150px;
top: 5px;
left: 5px;
cursor: pointer;
}
.dragging {
border: 4px yellow solid;
}
.drag-over {
background-color: #f4f4f4;
border-style: dashed;
}
.invisible {
display: none;
}
</style>
</head>
<body>
<div class="container">
<div class="droppable">
<!-- draggable可拖动标签 -->
<div class="draggable" draggable="true"></div>
</div>
<div class="droppable"></div>
<div class="droppable"></div>
<div class="droppable"></div>
<div class="droppable"></div>
</div>
<script>
// 查询draggable和droppable
const draggable = document.querySelector('.draggable');
const droppables = document.querySelectorAll('.droppable');
// 监听draggable的相关事件
// 开始拖动事件
draggable.addEventListener('dragstart', function dragStart() {
this.className += ' dragging';
setTimeout(() => {
this.className = 'invisible';
}, 0);
});
draggable.addEventListener('dragend', function dragEnd() {
this.className = 'draggable';
});
// 监听droppable的相关事件
for (const item of droppables) {
// ondragover - 当某被拖动的对象在另一对象容器范围内拖动时触发此事件
item.addEventListener('dragover', function dragOver(e) {
// 该方法将通知 Web 浏览器不要执行与事件关联的默认动作(如果存在这样的动作),比如阻止表单提交,阻止链接跳转。
e.preventDefault();
});
// ondragleave - 当被鼠标拖动的对象离开其容器范围内时触发此事件
item.addEventListener('dragleave', function dragLeave(e) {
this.className = 'droppable';
});
// ondragenter - 当被鼠标拖动的对象进入其容器范围内时触发此事件
item.addEventListener('dragenter', function dragEnter(e) {
e.preventDefault();
this.className += ' drag-over';
});
// ondrop - 在一个拖动过程中,释放鼠标键时触发此事件
item.addEventListener('drop', function dragDrop(e) {
this.className = 'droppable';
this.append(draggable);
});
}
</script>
</body>
</html>
效果如下:
ondragstart - 用户开始拖动元素时触发
ondrag - 元素正在拖动时触发
ondragend - 用户完成元素拖动后触发
释放目标时触发的事件:
ondragenter - 当被鼠标拖动的对象进入其容器范围内时触发此事件
ondragover - 当某被拖动的对象在另一对象容器范围内拖动时触发此事件
ondragleave - 当被鼠标拖动的对象离开其容器范围内时触发此事件
ondrop - 在一个拖动过程中,释放鼠标键时触发此事件