HTML5拖拽/拖放(drag & drop)详解

时间:2024-03-10 22:05:25
H5中拖拽属性:
draggable: auto | true | false
 
拖动事件:
 
- dragstart 在元素开始被拖动时触发
- dragend 在拖动操作完成时触发
- drag 在元素被拖动时触发
释放区事件:
 
dragenter 被拖动元素进入到释放区所占据得屏幕空间时触发
dragover 当被拖动元素在释放区内移动时触发
dragleave 当被拖动元素没有放下就离开释放区时触发
drop 当被拖动元素在释放区里放下时触发
案例: 实现div拖拽到指定区域效果:
效果:
初始效果:
拖拽过程中的效果:

拖拽到释放去 释放后的效果:

 

下面是这个操作的代码

<div class="box">
    <img id="one" draggable="true" src="./img/1.jpg" alt="">
    <img id="two" draggable="true" src="./img/2.jpg" alt="">
    <div class="drop"></div>
</div>
<script>
    var box = document.getElementByclassName(\'box\')[0];
    var drop = document.getElementsByClassName(\'drop\')[0];
    box.ondragstart = function (e) {
        console.log(\'dragstart\');
        e.dataTransfer.setData(\'id\',e.target.id);
    } 
    box.ondrag = function (e) {
        console.log(\'drag\',e.target.id);
    }
    box.ondragend = function (e) {
        console.log(\'dragend\')
    }
    drop.ondragenter = function (e) {
        console.log(\'dragenter\');
        e.preventDefault();
    }
    drop.ondragover = function (e) {
        console.log(\'dragover\');
        e.preventDefault();
        drop.innerHTML = \'\';
    }
    drop.ondragleave = function (e) {
        console.log(\'dragleave\');
        e.preventDefault();
    }
    drop.ondrop = function (e) {
        console.log(\'drop\');
        var imgId = e.dataTransfer.getData(\'id\');
        var img = document.getElementById(imgId).cloneNode(true);
        drop.appendChild(img);
    }
</script>
 1 <style>
 2     .demo * {
 3         float: left;
 4         width: 100px;
 5         height: 100px;
 6         border: 1px solid #000;
 7     }
 8     img {
 9         width: 100px;
10         height: 100px;
11         display: inline-block;
12     }
13     .drop {
14         width: 100px;
15         height: 100px;
16         border: 1px solid #000;
17     }
18 </style>