标签:
首先,为了使元素可拖动,把 draggable 属性设置为 true :< li draggable="true"> aaaa</li> 否则不会有效果
必须设置 dataTransfer 对象的setData方法 才能拖拽图片以外的其他标签
dataTransfer.setData() 方法 设置被拖数据的数据和值(key和 value)必须 是字符串, dataTransfer.getData() 方法 根据 key 获取value的 值
下面是一个简单的例子:
<!DOCTYPE> <html> <head> <meta charset="utf-8"> <style type="text/css"> li{ height: 20px; width: 100px; background: #e3f; margin: 20px; list-style: none; } div{ margin-top: 200px; width: 100px; height: 100px; background: red; } </style> <title>ni</title> <script type="text/javascript"> window.onload = function(){ var j = 0; var ul = document.getElementsByTagName("ul")[0]; var lis = document.getElementsByTagName("li"); var put = document.getElementById("put"); for (var i = 0; i < lis.length; i++) { lis[i].index = i; lis[i].ondragstart = function(ev){ var ev = ev||window.evnet; ev.dataTransfer.setData("index",this.index); this.style.backgroundColor = "#9f9"; } lis[i].ondrag = function(){ this.style.backgroundColor = "#ff9"; } lis[i].ondragend = function(){ this.style.backgroundColor = "#931"; } }; put.ondragenter = function(){ this.style.backgroundColor = "black"; } put.ondragover = function(ev){ ev.preventDefault(); this.style.backgroundColor = "blue"; } put.ondragleave = function(){ this.style.backgroundColor = "#931"; } put.ondrop = function(ev){ var ev = ev || window.evnet; this.style.backgroundColor = "#999"; ev.target.appendChild(lis[ev.dataTransfer.getData("index")]); //ul.removeChild(lis[ev.dataTransfer.getData("index")]); 加了这句话反而出问题,appendChild(e) 就是剪切的,当添加了子元素 e 后,会把原来的元素 e 给删除了 for (var i = 0; i < lis.length; i++) { lis[i].index = i; }; } } </script> </head> <body> <ul> <li draggable="true">aaaaa</li> <li draggable="true">bbbbb</li> <li draggable="true">ccccc</li> </ul> <div id="put"></div> </body>
标签:
原文地址:http://www.cnblogs.com/a-lonely-wolf/p/5313809.html