基于html5拖拽api实现列表的拖拽排序
html代码:
<ul ondrop="drop_handler(event);" ondragover="dragover_handler(event);"> <li draggable="true" ondragstart="dragstart_handler(event);">1</li> <li draggable="true" ondragstart="dragstart_handler(event);">2</li> <li draggable="true" ondragstart="dragstart_handler(event);">3</li> <li draggable="true" ondragstart="dragstart_handler(event);">4</li> <li draggable="true" ondragstart="dragstart_handler(event);">5</li> </ul>
js代码:
var uls = document.querySelector('ul'); var offsetTop = uls.offsetTop; var clientX = ''; var clientY = ''; var n = 0; function dragstart_handler(ev) { console.log("dragStart"); ev.target.setAttribute('id', 'test1') ev.dataTransfer.setData("text/plain", ev.target.id); } function dragover_handler(ev) { ev.preventDefault(); clientX = ev.clientX; clientY = ev.clientY; n = Math.round((clientY - offsetTop)/52) //52代指拖拽元素的高度 } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); console.log(n) var nodes = document.getElementById(data); uls.insertBefore(nodes, children(uls)[n]); nodes.removeAttribute('id'); ev.dataTransfer.clearData(); } function children(node){ var tmp = node.childNodes; var arr = []; tmp.forEach(function(item){ if(item.nodeType == 1){ arr.push(item); } }); return arr; }
效果展示: