使用html5元素实现拖拽交换位置,可用于排序
程序员文章站
2022-07-14 16:31:16
...
html:
<div ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)">拖拽元素1</div>
<div ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)">拖拽元素2</div>
<div ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)">拖拽元素3</div>
js:
<script type="text/javascript">
function allowDrop(ev)
{
ev.preventDefault();
}
var srcdiv = null;
function drag(ev,divdom)
{
srcdiv=divdom;
ev.dataTransfer.setData("text/html",divdom.innerHTML);
}
function drop(ev,divdom)
{
ev.preventDefault();
if(srcdiv != divdom){
srcdiv.innerHTML = divdom.innerHTML;
divdom.innerHTML=ev.dataTransfer.getData("text/html");
}
}
</script>