HTML5 拖拽效果实现

时间:2024-09-21 21:37:38
 <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
li {
list-style: none;
background: orange;
width: 180px;
height: 30px;
margin: 10px;
font:normal 12px/2em "微软雅黑";
text-align: center;
} #div1 {
width: 200px;
height: 200px;
background: #ff0000;
margin: 20px;
}
</style>
</head>
<body> <ul>
<li draggable="true">你爱我像谁</li>
<li draggable="true">选择</li>
<li draggable="true">胆小鬼</li>
<li draggable="true">再见</li>
<li draggable="true">少年游</li>
<li draggable="true">泡沫</li>
<li draggable="true">跟着感觉走</li>
<li draggable="true">浮夸</li>
<li draggable="true">光辉岁月</li>
</ul>
<script>
window.onload = function(){
var oUl = document.getElementsByTagName("ul")[0];
var oLi = document.getElementsByTagName('li');
var img = document.getElementsByTagName('img')[0];
for(var i = 0; i<oLi.length;i++){
oLi[i].index = i;
oLi[i].ondragstart = function(ev){
this.style.backgroundColor = "yellow";
ev.dataTransfer.setData('index',this.index);
ev.dataTransfer.effectAllowed = "copy";
};
oLi[i].ondragend = function(ev){
this.style.backgroundColor = "orange";
};
oLi[i].ondragover= function(ev){
ev.preventDefault();
};
oLi[i].ondrop = function(ev){
var flag = ev.dataTransfer.getData('index');
var node = oLi[flag];
oUl.insertBefore(node,this.nextSibling); for(var i = 0; i<oLi.length;i++){
oLi[i].index = i;
}
};
}
}
</script>
</body>
</html>