JavaScript拖拽API的简单使用

演示效果:

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .father {
            display: flex;
        }

        #box1,
        #box2 {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100px;
            height: 100px;
            border: 1px solid #000;
        }

        #box2 {
            margin-left: 100px;
        }
    </style>
</head>

<body>
    <div class="father">
        <div id="box1"></div>
        <div id="box2">
            <!-- 将图片设置为可拖拽状态 -->
            <img id="pic" draggable="true" src="./images/car.png">
        </div>
    </div>

    <script>
        const box1 = document.querySelector('#box1');
        const pic = document.querySelector('#pic');

        // 将鼠标指针悬停在box1元素上,并拖拽其他元素时
        box1.addEventListener('dragover', e => {
            e.preventDefault(); // 阻止默认行为
        })

        // 当拖放操作在目标元素上执行时触发
        box1.addEventListener('drop', e => {
            const id = e.dataTransfer.getData('text/plain'); // 获取拖拽数据
            e.target.appendChild(document.getElementById(id)); // 将拖拽的元素添加到目标元素中
        })

        // 拖放开始时触发
        pic.addEventListener('dragstart', e => {
            console.log('开始拖拽', e);
            e.dataTransfer.setData('text/plain', e.target.id); // 设置拖拽数据
        })

        // 拖放操作结束时触发
        pic.addEventListener('dragend', e => {
            console.log('结束拖拽', e);
        })
    </script>
</body>

</html>
相关推荐
码兄科技18 小时前
Java AI智能体开发实战:从零构建智能对话系统指南
java·开发语言·人工智能
Drone_xjw19 小时前
从 GDB 到 CDB:C/C++ 程序调试的两把“手术刀”
c语言·开发语言·c++
SL-staff20 小时前
智慧园区2000+设备统一管理:JVS-IoT如何降低运维成本40%
java·开发语言·物联网·智慧园区·设备管理·运维优化·jvs-iot
2zcode21 小时前
基于MATLAB图像处理的饮料瓶灌装液位检测系统设计与实现
开发语言·图像处理·matlab
必须得开心呀1 天前
QT解决中文乱码问题
开发语言·qt
Jackson__1 天前
为了拯救我的腰椎和颈椎,我做了款浏览器插件!
前端·javascript·开源
林小帅1 天前
NestJS v11 + Prisma v7 ESM 迁移配置解析
前端·javascript·后端
这不小天嘛1 天前
JAVA八股——redis篇
java·开发语言·redis
Hilaku1 天前
为什么你的大文件断点续传,一遇到弱网就崩溃?
前端·javascript·程序员
逝水无殇1 天前
C# 字符串(String)详解
开发语言·后端·c#