首页 > 代码库 > HTML5 拖拽效果实现

HTML5 拖拽效果实现

 1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4     <meta charset="UTF-8"> 5     <title></title> 6     <style> 7         li { 8             list-style: none; 9             background: orange;10             width: 180px;11             height: 30px;12             margin: 10px;13             font:normal 12px/2em "微软雅黑";14             text-align: center;15         }16 17         #div1 {18             width: 200px;19             height: 200px;20             background: #ff0000;21             margin: 20px;22         }23     </style>24 </head>25 <body>26 27 <ul>28     <li draggable="true">你爱我像谁</li>29     <li draggable="true">选择</li>30     <li draggable="true">胆小鬼</li>31     <li draggable="true">再见</li>32     <li draggable="true">少年游</li>33     <li draggable="true">泡沫</li>34     <li draggable="true">跟着感觉走</li>35     <li draggable="true">浮夸</li>36     <li draggable="true">光辉岁月</li>37 </ul>38 <script>39     window.onload = function(){40         var oUl = document.getElementsByTagName("ul")[0];41         var oLi = document.getElementsByTagName(li);42         var img = document.getElementsByTagName(img)[0];43         for(var i = 0; i<oLi.length;i++){44             oLi[i].index = i;45             oLi[i].ondragstart = function(ev){46                   this.style.backgroundColor = "yellow";47                   ev.dataTransfer.setData(index,this.index);48                   ev.dataTransfer.effectAllowed = "copy";49             };50             oLi[i].ondragend = function(ev){51                 this.style.backgroundColor = "orange";52             };53             oLi[i].ondragover= function(ev){54                 ev.preventDefault();55             };56             oLi[i].ondrop = function(ev){57                 var flag = ev.dataTransfer.getData(index);58                 var node = oLi[flag];59                 oUl.insertBefore(node,this.nextSibling);60 61                 for(var i = 0; i<oLi.length;i++){62                     oLi[i].index = i;63                 }64             };65         }66     }67 </script>68 </body>69 </html>

 

HTML5 拖拽效果实现