<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>task2_5</title>
<style>
* {
padding: 0;
margin: 0;
list-style: none;
}
#wrap {
margin: 100px; auto;
width: 980px;
}
ul {
position: relative;
height: 310px;
float: left;
margin-left:200px;
border: 1px solid #10a399;
}
li {
width: 200px;
height: 30px;
background: #c1f3f3;
border-bottom: 1px solid #10a399;
text-align: center;
color: #999;
line-height: 30px;
}
</style>
</head>
<body>
<p id="wrap">
<ul id="ul1">
<li id="move">1</li>
<li class="move">2</li>
<li class="move">3</li>
<li class="move">4</li>
<li class="move">5</li>
</ul>
</p>
</body>
<script type="text/javascript">
var ul = document.getElementById('ul1');
var aLi = ul.getElementsByTagName('li');
var liTop = aLi[0].offsetTop;
var liHeight = aLi[0].offsetHeight;
for(var i=0; i<aLi.length; i++){ drag(aLi[i]); }
function drag(obj) {
obj.onmousedown = function(ev) {
var ev = ev || event;
var blank = document.createElement('li');
ul.insertBefore(blank,obj.nextSibling);
blank.style.visibility = 'hidden';
obj.style.left = obj.offsetLeft + 'px';
obj.style.top = obj.offsetTop + 'px';
obj.style.position = "absolute";
obj.style.zIndex = '999';
obj.style.background = '#e0543e';
var disX = ev.clientX - obj.offsetLeft;
var disY = ev.clientY - obj.offsetTop;
if (obj.setCapture) {obj.setCapture();}
document.onmousemove = function(ev) {
var ev = ev || event;
var L = ev.clientX - disX;
var T = ev.clientY - disY;
var n = Math.round((T-liTop)/liHeight + 1);
ul.insertBefore(blank,ul.children[n]);
obj.style.left = L + 'px';
obj.style.top = T + 'px';
};
document.onmouseup = function() {
ul.insertBefore(obj,blank);
obj.removeAttribute('style');
ul.removeChild(blank);
document.onmousemove = null;
if (obj.releaseCapture) {obj.releaseCapture();}
};
return false;
};
}
</script>
</html>
最近学了面向对象的相关知识,但是写起来还是乱七八糟的。
如果能用事件代理最好
另外还想再放一个ul,形成可以两个ul可以相互拖拽排序
万分感谢万分感谢万分感谢
将你的代码简单改造了一下,首先将下面代码保存在一个叫做
drag.js
的文件中这个简单封装的库基本上就是你的代码稍微修改而来,当然改进的空间还很大,运用了事件委托的方式添加事件。
因为事件是添加到父级ul的上面,因此,调用的时候,只需将ul的id传入即可,使用方式如下
你也可以用如下完整代码来查看效果