拖拽小案例(以克隆的方式实现)

需求: 当文件夹file被拖拽到box2时,将文件夹file克隆一份并将其append到box2中(只克隆生成一次);

<!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>
.box1 {
width : 300 px;
height : 300 px;
background-color : pink;
}

.box2 {
width : 300 px;
height : 300 px;
background-color : skyblue;
}

.file {
width : 100 px;
height : 100 px;
background-color : red;
line-height : 100 px;
text-align : center;
}
</ style>
</ head>

< body>
< h2>box1</ h2>
< div class= " box1 ">
<!-- draggable="true" 这个属性可以让元素可以拖拽 -->
< div class= " file " draggable= " true ">
文件夹
</ div>
</ div>
< h2>box2</ h2>
< div class= " box2 "></ div>
</ body>

</ html>
< script>
var box1 = document. querySelector( ' .box1 ');
var box2 = document. querySelector( ' .box2 ');
var file = document. querySelector( ' .file ');
//封装函数,参数ele 要移动的元素,参数box 移动到的位置
function move( ele, box) {
// ondragover拖拽事件,当被拖拽的元素经过时触发
box. ondragover = function ( target) {
//默认是不接受被拖拽元素的,所以要禁用默认事件
target. preventDefault();
}

var flag = true; //假设ele元素还没有被克隆到 box

ele. onmousedown = function () {

var $clone = this. cloneNode( true);
$clone.style.backgroundColor = ' green ';

box. ondrop = function () {
if (flag == true) {
this. appendChild($clone);
flag = false; // ele元素已经被克隆到box,flag变为false
}
}

}
}
// 调用函数
move(file,box2);
</ script>


猜你喜欢

转载自blog.csdn.net/qq_42209630/article/details/80476070