样式部分:
<style>
.item {
width: 500px;
text-align: center;
margin-bottom: 5px;
height: 40px;
line-height: 40px;
border-radius: 5px;
color: #fff;
margin: 5 auto;
background-color: red;
}
.item.moving {
background: transparent;
color: transparent;
border: 1px dashed #ccc;
}
</style>
<div class="container">
<div id="apple" draggable="true" class="item">苹果</div>
<div id="banana" draggable="true" class="item">香蕉</div>
<div id="ss" draggable="true" class="item">黄梨</div>
<div id="sdf" draggable="true" class="item">西瓜</div>
<div id="5sdf" draggable="true" class="item">葡萄</div>
<div id="dfdf" draggable="true" class="item">留恋</div>
</div>
<script>
const con = document.querySelector('.container');
let selfNode;
con.ondragstart = e => {
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('Text', e.target.id);
console.log(e);
setTimeout(() => {
e.target.classList.add('moving');
}, 0);
selfNode = e.target;
};
con.ondragover = e => {
e.preventDefault();
};
con.ondragenter = e => {
e.preventDefault();
console.log('enter', e);
if (e.target === con || e.target === selfNode) {
return;
}
const children = Array.from(con.children);
const selfIndex = children.indexOf(selfNode);
const targetIndex = children.indexOf(e.target);
console.log(selfNode, e.target);
if (selfIndex < targetIndex) {
con.insertBefore(selfNode, e.target.nextElementSibling);
} else {
con.insertBefore(selfNode, e.target);
}
};
con.ondragend = e => {
selfNode.classList.remove('moving');
};
</script>