<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<style>
ul {
list-style: none;
margin: 200px;
font-size: 0;
}
.ele {
font-size: 16px;
100px;
height: 40px;
border: 1px solid #999;
background: #EA6E59;
margin: 2px 0;
border-radius: 10px;
padding-left: 10px;
color: white;
cursor: move;
}
</style>
<form id="form1" runat="server">
<div>
<ul id="container">
<li class="ele" draggable="true">1</li>
<li class="ele" draggable="true">2</li>
<li class="ele" draggable="true">3</li>
<li class="ele" draggable="true">4</li>
<li class="ele" draggable="true">5</li>
<li class="ele" draggable="true">6</li>
<li class="ele" draggable="true">7</li>
<li class="ele" draggable="true">8</li>
</ul>
</div>
</form>
</body>
</html>
<script>
var node = document.querySelector("#container");
var draging = null;
//使用事件委托,将li的事件委托给ul
node.ondragstart = function (event) {
//firefox设置了setData后元素才能拖动!!!!
event.dataTransfer.setData("te", event.target.innerText); //不能使用text,firefox会打开新tab
draging = event.target;
}
node.ondragover = function (event) {
event.preventDefault();
var target = event.target;
//因为dragover会发生在ul上,所以要判断是不是li
if (target.nodeName === "LI" && target !== draging) {
//_index是实现的获取index
if (_index(draging) < _index(target)) {
target.parentNode.insertBefore(draging, target.nextSibling);
} else {
target.parentNode.insertBefore(draging, target);
}
}
}
function _index(el) {
var index = 0;
if (!el || !el.parentNode) {
return -1;
}
while (el && (el = el.previousElementSibling)) {
index++;
}
return index;
}
</script>