OBJUI

手写原生拖拽布局:基于HTML、CSS和JavaScript的简易实现

2025-03-25 14:02:16 23

通过原生HTML、CSS和JavaScript实现了一个轻量级拖拽布局功能。利用HTML5的draggable属性与拖放事件监听,结合CSS动态调整元素位置和视觉反馈,用户可自由拖拽页面元素并实时更新布局结构。代码简洁高效,无需依赖第三方库,适合快速集成到管理后台、可视化编辑器等场景。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>带数据获取功能的拖拽布局示例</title>
    <style>
        .draggable {
            width: 100px;
            height: 100px;
            background-color: #3498db;
            color: white;
            text-align: center;
            line-height: 100px;
            cursor: move;
            position: absolute;
        }

        button {
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div id="box1" class="draggable">Box 1</div>
    <div id="box2" class="draggable">Box 2</div>
    <button id="getLayoutDataBtn">获取布局数据</button>
    <pre id="layoutDataOutput"></pre>

    <script>
        const draggables = document.querySelectorAll('.draggable');
        const getLayoutDataBtn = document.getElementById('getLayoutDataBtn');
        const layoutDataOutput = document.getElementById('layoutDataOutput');

        draggables.forEach(draggable => {
            let isDragging = false;
            let offsetX, offsetY;

            draggable.addEventListener('mousedown', (e) => {
                isDragging = true;
                offsetX = e.clientX - draggable.offsetLeft;
                offsetY = e.clientY - draggable.offsetTop;
            });

            document.addEventListener('mousemove', (e) => {
                if (isDragging) {
                    draggable.style.left = (e.clientX - offsetX) + 'px';
                    draggable.style.top = (e.clientY - offsetY) + 'px';
                }
            });

            document.addEventListener('mouseup', () => {
                isDragging = false;
            });
        });

        getLayoutDataBtn.addEventListener('click', () => {
            const layoutData = [];
            draggables.forEach(draggable => {
                const elementData = {
                    id: draggable.id,
                    tagName: draggable.tagName,
                    style: {
                        left: draggable.style.left,
                        top: draggable.style.top,
                        width: draggable.style.width,
                        height: draggable.style.height,
                        backgroundColor: draggable.style.backgroundColor,
                        color: draggable.style.color
                    },
                    innerHTML: draggable.innerHTML
                };
                layoutData.push(elementData);
            });
            layoutDataOutput.textContent = JSON.stringify(layoutData, null, 2);
        });
    </script>
</body>

</html>    
更多精彩,请关注公众号

微信公众号