最簡單的拖拽效果

咱也不多BB,上代碼,拉走看

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .box1, .box2 {
            width: 300px;
            height: 400px;
            border: 2px solid #000;
            display: inline-block;
        }
        .child {
            width: 100px;
            height: 100px;
            background: yellow;
        }
    </style>
</head>
<body>
    <div class="box1" ondrop="ing(event)" ondragover="other(event)">
        <div id="child" class="child" draggable="true" ondragstart="start(event)"></div>
    </div>
    <div class="box2" ondrop="ing(event)" ondragover="other(event)"></div>

    <script>
        // 執行順序
        // 1、拖動鬆開鼠標 ondragover
        //     默認動作會阻止ondrop觸發
        // 2、觸發 ondrop
        function start(e) {
            e.dataTransfer.setData('text', e.target.id)
        }
        function ing(e) {
            e.preventDefault()
            var data = event.dataTransfer.getData('text')
            e.target.appendChild(document.getElementById(data))
        }
        function other(e) {
            e.preventDefault()
        }
    </script>
</body>
</html>

 

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