html5 drag拖放實現兩個div互換

參考網址:https://github.com/sunshine940326/drag

<!DOCTYPE html>
<!DOCTYPE HTML>
<html>
<head>
    <style type="text/css">
        #div1
        {float:left; width:100px; height:35px; margin:10px;padding:10px;border:1px solid #aaaaaa;}
        #div2
        {float:left; width:200px; height:135px; margin:10px;padding:10px;border:1px solid #aaaaaa;}

    </style>
    <script type="text/javascript">
        function allowDrop(ev)
        {
            ev.preventDefault();
        }

        var srcdiv = null;
        function drag(ev,divdom)
        {
            srcdiv=divdom;
            ev.dataTransfer.setData("text/html",divdom.innerHTML);
        }

        function drop(ev,divdom)
        {
            ev.preventDefault();
            if(srcdiv != divdom){
                srcdiv.innerHTML = divdom.innerHTML;
                divdom.innerHTML=ev.dataTransfer.getData("text/html");
            }
        }
    </script>
</head>
<body>

<div id="div1" ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)">
    <p>ni hao!</p>
</div>
<div id="div2" ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)">
    <p>Hello world!</p>
</div>

</body>
</html>

 

本篇發表於 程式設計。將永久鏈結加入書籤。