<!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 type="text/css">
.box {
width: 100px;
height: 35px;
margin: 10px;
padding: 10px;
border: 1px solid #aaaaaa;
}
.content {
border: solid 1px red;
}
.content>.item {
border: solid 1px red;
}
.item>.title {
background-color: aqua;
}
.item>.list>ul>li:nth-child(1) {
background-color: brown;
}
.item>.list>ul>li:nth-child(2) {
background-color: bisque;
}
</style>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
console.log('开始');
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
console.log('结束');
console.log(ev);
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
console.log(data);
console.log(ev.target.attributes['dragoverid'].nodeValue);
// 获取拖拽追加DOM的id
let _targetId = ev.target.attributes['dragoverid'].nodeValue;
// 把拖拽的DOM放在指定目标DOM下
document.getElementById(_targetId).appendChild(document.getElementById(data))
// ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<ul class="content">
<li class="item" dragoverId="dragAddLi1" ondrop="drop(event)" ondragover="allowDrop(event)">
<div class="title" dragoverId="dragAddLi1">1</div>
<div class="list" dragoverId="dragAddLi1">
<ul id="dragAddLi1">
<li draggable="true" dragoverId="dragAddLi1" ondragstart="drag(event)" id="li1">11</li>
<li draggable="true" dragoverId="dragAddLi1" ondragstart="drag(event)" id="li2">12</li>
</ul>
</div>
</li>
<li class="item" dragoverId="dragAddLi2" ondrop="drop(event)" ondragover="allowDrop(event)">
<div class="title" dragoverId="dragAddLi2">2</div>
<div class="list" dragoverId="dragAddLi2">
<ul id="dragAddLi2">
<li draggable="true" dragoverId="dragAddLi2" ondragstart="drag(event)" id="li3">21</li>
<li draggable="true" dragoverId="dragAddLi2" ondragstart="drag(event)" id="li4">22</li>
</ul>
</div>
</li>
</ul>
</body>
</html>
参考资料链接:https://www.runoob.com/html/html5-draganddrop.html