HTML + javascript implement a draggable list 一个可以拖拽交换顺序的列表
Reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragover_event
<body>
<style type="text/css">
.draggable {
text-align: center;
background: red;
width: 20px;
height: 20px;
margin: 2px;
}
</style>
<div>
<div class='draggable' id='1' draggable='true'>1</div>
<div class='draggable' id='2' draggable='true'>2</div>
<div class='draggable' id='3' draggable='true'>3</div>
<div class='draggable' id='4' draggable='true'>4</div>
</div>
<script type="text/javascript">
let dragging = null
document.querySelectorAll('.draggable')
.forEach(e => {
e.addEventListener('dragstart', e=>{
dragging=e.target
})
e.addEventListener('dragenter', e=>{
e.preventDefault()
const target = e.target
const draggingId = parseInt(dragging.id)
const targetId = parseInt(target.id)
target.id = draggingId
dragging.id = targetId
if (targetId > draggingId) {
dragging.insertAdjacentElement('beforebegin', target)
} else {
dragging.insertAdjacentElement('afterend', target)
}
})
e.addEventListener('dragover', e=>{
e.preventDefault()
})
e.addEventListener('drop', e=>{
e.preventDefault()
})
})
</script>
</body>
+V why_null 请备注:from博客园