演示效果:
html
<!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>
.father {
display: flex;
}
#box1,
#box2 {
display: flex;
align-items: center;
justify-content: center;
width: 100px;
height: 100px;
border: 1px solid #000;
}
#box2 {
margin-left: 100px;
}
</style>
</head>
<body>
<div class="father">
<div id="box1"></div>
<div id="box2">
<!-- 将图片设置为可拖拽状态 -->
<img id="pic" draggable="true" src="./images/car.png">
</div>
</div>
<script>
const box1 = document.querySelector('#box1');
const pic = document.querySelector('#pic');
// 将鼠标指针悬停在box1元素上,并拖拽其他元素时
box1.addEventListener('dragover', e => {
e.preventDefault(); // 阻止默认行为
})
// 当拖放操作在目标元素上执行时触发
box1.addEventListener('drop', e => {
const id = e.dataTransfer.getData('text/plain'); // 获取拖拽数据
e.target.appendChild(document.getElementById(id)); // 将拖拽的元素添加到目标元素中
})
// 拖放开始时触发
pic.addEventListener('dragstart', e => {
console.log('开始拖拽', e);
e.dataTransfer.setData('text/plain', e.target.id); // 设置拖拽数据
})
// 拖放操作结束时触发
pic.addEventListener('dragend', e => {
console.log('结束拖拽', e);
})
</script>
</body>
</html>