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

本文介绍了一种使用HTML和JavaScript实现的简单方法,当一个代表文件夹的元素被拖拽到指定区域时,该元素会被克隆并在新位置显示。此功能通过监听dragover和drop事件,并利用cloneNode方法来完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求: 当文件夹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: 300px;
height: 300px;
background-color: pink;
}

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

.file {
width: 100px;
height: 100px;
background-color: red;
line-height: 100px;
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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值