js 實現拖動dom元素並交換位置

效果圖如下:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        body {
            display: flex;
            padding: 100px;
        }
        div {
            width: 100px;
            height: 100px;
            text-align: center;
            line-height: 100px;
            color: white;
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <!-- 設置draggable爲true使其變爲可拖動狀態 -->
    <div style="background: purple" draggable="true">DIV1</div>
    <div style="background: orange" draggable="true">DIV2</div>
    <div style="background: aqua" draggable="true">DIV3</div>
</body>
<script type="text/javascript">
    // 得到你需要進行拖動變換的所有dom元素
    let div = document.getElementsByTagName("div")

    let container = null
    for(let i = 0; i < div.length; i++) {
        div[i].ondragstart = function() {
            // 當拖動其中一個元素時,this的指向便是你所拖動的元素,將它存在container
            container = this
        }
        // 默認的當你dragover的時候會阻止你做drop的操作,所以需要取消這個默認
        div[i].ondragover = function() {
            event.preventDefault()
        }
        // 當拖動結束時,給拖動div所在位置下面的div做drop事件,注意drop時this的指向發生改變
        div[i].ondrop = function()
        {
            if(container != null && container != this)
            {
                console.log("now this:",this)
                console.log("now container:",container)
                let temp = document.createElement("div")
                document.body.replaceChild(temp,this)
                document.body.replaceChild(this,container)
                document.body.replaceChild(container,temp)
            }
        }
    }
</script>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章