html5新的拖拽 只支持Internet Explorer 9、Firefox、Opera 12、Chrome 以及 Safari 5 支持拖放。
来一个实例:
<!DOCTYPE html> <html> <head> <style type="text/css"> table td{ width:120px; height:50px; border:1px solid #000; } table td div.dragDiv{ margin:3px; border:1px solid #444; padding:3px; cursor:pointer; } </style> </head> <body> <table> <tr> <td> <div class="dragDiv">我是要拖动的</div> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr><tr> <td> <div class="dragDiv">我是第二个</div> </td> <td></td> <td></td> <td></td> <td></td> </tr> </table> <p>请把 W3School 的图片拖放到矩形中:</p> <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <br /> <img id="drag1" src="images/bigSwim7.png" draggable="true" ondragstart="drag(event)" /> <script src="js/jquery-1.12.0.min.js"></script> <script type="text/javascript"> //对表格中的DIV拖拽 var tempData = ""; $("table td div.dragDiv").each(function () { this.draggable = true; this.ondragstart = function (e) { if (this == e.target) { e.dataTransfer.setData("id", e.target.innerHTML); tempData = this; } } }); $("table td").each(function () { this.ondragover = function (e) { e.preventDefault(); } this.ondrop = function (e) { if (this == e.target) { e.preventDefault(); e.target.appendChild(tempData); tempData = ""; } } }) //图片拖拽 function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("Text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); } </script> </body> </html>
时间: 2024-11-11 22:03:30