拖动基本实现

时间:2022-01-24 10:15:29

拖动相关事件:dragstart, drag, dragenter, dragleave, dragover, drop, dragend.

如下图,将三个圆拖动到矩形里面:

拖动基本实现 拖动基本实现

HTML结构:

<div class="row">
    <div class="span-6 dragTarg"></div>
</div>
<div class="row">
    <div class="span-6 dragItems">
        <div draggable="true" class="red"></div>
        <div draggable="true" class="blue"></div>
        <div draggable="true" class="green"></div>
    </div>
</div>

CSS:

.row{
  margin: 10px;
}

.row .dragTarg{
  width: 100px;
  height: 40px;
  background-color: #ccc;
}
.dragTarg div,
.dragItems div{
  width: 30px;
  height: 30px;
  border-radius: 15px;
  display: inline-block;
}

.red{background-color: #f00}
.blue{background-color: #00f}
.green{background-color: #0f0}

JS:

var circles = document.querySelectorAll('.dragItems div');
for(var i=0;i<circles.length;i++){
  var circle = circles[i];
  circle.addEventListener('dragstart',onDragStart,false);
  circle.addEventListener('dragend',onDragEnd,false);
}

function onDragStart(e){
  this.style.border = '5px solid #000';
 //拖动某个圆形时,保存其样式名(或者id),以便后面能通过样式名找到。
  e.dataTransfer.setData('text',this.className);
}
function onDragEnd(e){
  this.style.border = 'none';
}

var dragTarg = document.querySelector('.dragTarg');
dragTarg.addEventListener('dragenter', onDragEnter);
function onDragEnter(e){
  this.style.border = '3px #aaa dashed';
}

dragTarg.addEventListener('dragover', onDragOver);
function onDragOver(e){
   //只有阻止了dragover的默认行为,才会有drop事件发送出来。
  //否则无法监听到drop事件。
  e.preventDefault();
}
dragTarg.addEventListener('drop',onDrop,false);
function onDrop(e){
  //e.preventDefault();
  
  var className = e.dataTransfer.getData('text');
 //根据保存的样式名,找到拖动的圆形
  var ele = document.querySelector('.dragItems .'+className);
 //将其添加到矩形中,即原来的圆被移走。
  this.appendChild(ele);
}