拖动盒子demo


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .from, .to {
            width: 300px;
             height: 200px;
            background-color: yellowgreen;
        }

        .box1, .box2 {
            width: 100px;
            height: 100px;
            margin: 10px;
            float: left;
            background-color: red;
        }
    </style>
</head>
<body>
   <h3>从这个盒子</h3> 
   <div class="from">
       <div class="box1">111</div>
       <div class="box2">222</div>
   </div>

   <h3>到这个盒子</h3>
   <div class="to"></div>
</body>
</html>

<script>
    //目标盒子
    var to = document.querySelector(".to");
    var from = document.querySelector(".from");
    var box1 = document.querySelector(".box1");
    var box2 = document.querySelector(".box2");

    var littleBox;

    box1.onmousedown = function() {
        box1.setAttribute("draggable", true);
        littleBox = box1;
    }

    box2.onmousedown = function() {
        box2.setAttribute("draggable", true);
        littleBox = box2;
    }

    //必须实现目标盒子的两个方法
    to.ondragover = function(event) {
        event.preventDefault();
    }

    to.ondrop = function() {
        this.appendChild(littleBox);
    }
    //必须实现目标盒子的两个方法
    from.ondragover = function (event) {
        event.preventDefault();
    }

    from.ondrop = function () {
        this.appendChild(littleBox);
    }
</script>

posted on 2017-12-21 19:59  ouruixi  阅读(109)  评论(0)    收藏  举报

导航