HTML5拖拽表格中单元格间的数据库

效果图:

 

代码:

<!DOCTYPE HTML>
<html>
<head>
    <script src="jquery-min.js"></script>
    <style>
    td{
        width:100px;
        height:80px;
        border:1px solid #444;
        cursor:pointer;
    }
    div{
        background:#0094ff;
        padding:5px;
        border:1px solid #444;
    }
    </style>

    <script type="text/javascript">
        $(function () {
            $("div").each(function () {
                this.draggable = true;
                this.ondragstart = function (e) {
                    e.dataTransfer.setData("id", e.target.id);
                };
                this.ondragend = function (e) {
                    $("td").css("background","");
                }
            })

            $("td").each(function () {
                this.ondragenter = function (e) {
                    $(this).css("background", "yellow");
                }
                this.ondragover = function (e) {
                    e.preventDefault();
                }
                this.ondragleave = function (e) {
                    $(this).css("background", "");
                }
                this.ondrop = function (e) {
                    e.preventDefault();
                    $(this).append($(document.getElementById(e.dataTransfer.getData("id"))));
                }
                
            })
        })
    </script>
</head>
<body>
       
    <table>
        <tr>
            <td>
                <div id="div1">1111111111</div>
            </td>
            <td>
                <div id="div2">222222222</div>
            </td>
            <td>
                <div id="div3">3333333333</div>
            </td>
            <td>
                <div id="div4">44444444444</div>
            </td>
        </tr>
    </table>

</body>
</html>

这里要注意这句 this.ondrop = function (e) { e.preventDefault(); $(this).append($(document.getElementById(e.dataTransfer.getData("id")))); }

其中$(this).append($(document.getElementById(e.dataTransfer.getData("id")))); 这句本来是下面这样的

   e.target.appendChild(document.getElementById(e.dataTransfer.getData("id")));

如果上面写时发现,在拖拽div层时有可能拖拽到另一个div层上,这是事件向传递,上网没有找到解决方法,所以只接使用对td追加的方法解决问题了。

 

posted @ 2015-10-18 16:34  lunawzh  阅读(322)  评论(0编辑  收藏  举报