1. 程式人生 > >HTML5拖拽/拖放(drag & drop)詳解

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

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>