知识点:
案例:
实例代码:
<!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>
*{
margin: 0;
padding: 0;
}
.left,.right{
margin: 30px;
width: 300px;
min-height: 30px;
border: 2px solid #ccc;
list-style: none;
}
li.item{
line-height: 30px;
text-align: center;
}
li.drag {
color: #fff;
background-color: bisque;
}
.right.over,.left.over{
border: 2px dashed rgb(118, 208, 157);
}
</style>
</head>
<body>
<ul class="left">
<li class="item" draggable="true">item 1</li>
<li class="item" draggable="true">item 2</li>
<li class="item" draggable="true">item 3</li>
<li class="item" draggable="true">item 4</li>
<li class="item" draggable="true">item 5</li>
</ul>
<ul class="right"></ul>
<script>
const leftElement = document.querySelector(".left");
const rightElement = document.querySelector(".right");
const items = document.querySelectorAll(".item");
let currentDragItem = null;
items.forEach(itemElement => {
itemElement.ondragstart = function (e) {
this.classList.add("drag");
currentDragItem = this;
}
itemElement.ondragend = function (e) {
this.classList.remove("drag");
}
});
leftElement.ondragover = rightElement.ondragover = function (e) {
if(!this.contains(currentDragItem)){
e.preventDefault();
this.classList.add("over");
}
}
leftElement.ondragleave = rightElement.ondragleave = function () {
this.classList.remove("over");
}
leftElement.ondrop = rightElement.ondrop = function (e) {
e.preventDefault();
e.stopPropagation();
this.appendChild(currentDragItem);
currentDragItem = null;
this.classList.remove("over");
}
</script>
</body>
</html>