You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript自动生成Div并设置为不影响页面的装饰元素

全屏可交互装饰方块实现方案

核心实现思路

  • 放弃Grid布局,采用绝对定位实现方块自由移动,不受布局结构限制
  • 基于屏幕宽高计算所需方块数量,批量生成直至填满可视区域
  • 将主容器设置为overflow: hidden,确保方块移出屏幕时不会撑开body
  • 绑定刷新按钮点击事件,触发方块的重新生成逻辑

完整全屏代码片段

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Decor Squares</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body, html {
            width: 100vw;
            height: 100vh;
            overflow: hidden;
        }
        #container {
            width: 100%;
            height: 100%;
            position: relative;
            overflow: hidden;
            background-color: #f0f0f0;
        }
        .refresh-btn {
            position: fixed;
            top: 1rem;
            left: 1rem;
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 4px;
            background-color: #2196F3;
            color: white;
            cursor: pointer;
            z-index: 1000;
            font-size: 1rem;
        }
        .refresh-btn:hover {
            background-color: #1976D2;
        }
        .square {
            position: absolute;
            width: 50px;
            height: 50px;
            background-color: rgba(33, 150, 243, 0.7);
            cursor: grab;
            transition: background-color 0.2s;
        }
        .square:active {
            cursor: grabbing;
            background-color: rgba(33, 150, 243, 1);
        }
    </style>
</head>
<body>
    <div id="container">
        <button class="refresh-btn" id="refreshBtn">刷新方块</button>
    </div>

    <script>
        const container = document.getElementById('container');
        const refreshBtn = document.getElementById('refreshBtn');
        const squareSize = 50; // 方块大小
        const gap = 5; // 方块间距

        // 生成填满屏幕的方块
        function generateSquares() {
            // 清空现有方块
            container.querySelectorAll('.square').forEach(sq => sq.remove());
            
            const screenWidth = window.innerWidth;
            const screenHeight = window.innerHeight;
            
            // 计算每行/每列可容纳的方块数量
            const cols = Math.floor((screenWidth + gap) / (squareSize + gap));
            const rows = Math.floor((screenHeight + gap) / (squareSize + gap));
            
            // 批量生成方块
            for (let i = 0; i < rows; i++) {
                for (let j = 0; j < cols; j++) {
                    const square = document.createElement('div');
                    square.classList.add('square');
                    // 设置初始位置
                    square.style.left = `${j * (squareSize + gap)}px`;
                    square.style.top = `${i * (squareSize + gap)}px`;
                    
                    // 绑定拖拽交互
                    initDrag(square);
                    
                    container.appendChild(square);
                }
            }
        }

        // 方块拖拽逻辑
        function initDrag(square) {
            let isDragging = false;
            let startX, startY, offsetX, offsetY;

            square.addEventListener('mousedown', (e) => {
                isDragging = true;
                startX = e.clientX;
                startY = e.clientY;
                offsetX = square.offsetLeft;
                offsetY = square.offsetTop;
                square.style.zIndex = 100;
            });

            document.addEventListener('mousemove', (e) => {
                if (!isDragging) return;
                const dx = e.clientX - startX;
                const dy = e.clientY - startY;
                square.style.left = `${offsetX + dx}px`;
                square.style.top = `${offsetY + dy}px`;
            });

            document.addEventListener('mouseup', () => {
                isDragging = false;
                square.style.zIndex = 1;
            });
        }

        // 初始化生成+绑定刷新事件
        generateSquares();
        refreshBtn.addEventListener('click', generateSquares);

        // 窗口大小改变时重新生成(可选)
        window.addEventListener('resize', generateSquares);
    </script>
</body>
</html>

关键细节说明

  • 防止body撑开:通过给html、body和主容器设置overflow: hidden,确保方块移出可视区域时不会触发滚动条或撑开页面
  • 批量生成逻辑:根据屏幕宽高和方块尺寸、间距,计算出刚好填满屏幕的方块数量,避免冗余或留白
  • 交互优化:拖拽时提升方块层级,防止被其他方块遮挡,释放后恢复层级;添加鼠标状态变化提升体验
  • 刷新功能:点击按钮时先清空现有方块,再重新生成新的方块布局

内容的提问来源于stack exchange,提问作者Berk Efe Keskin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:55:22