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

如何用JavaScript在HTML中添加嵌套Div?笔记应用嵌套Div异常排查

问题修复方案

核心问题分析

  1. 重复ID冲突:每次生成的容器和头部都用相同ID,HTML中ID必须唯一,导致后续生成的元素无法正确应用CSS样式。
  2. 文本层级重叠:父容器直接设置textContent,子div插入后会和父容器文本重叠,导致子div显示异常。
  3. 拖拽逻辑缺失:仅设置了拖拽光标样式,没有实现实际的拖拽交互功能。

修正后代码

CSS(改用class选择器)
.note-container {
    position: absolute;
    background-color: pink;
    border: 1px solid black;
    width: 200px;
    height: 200px;
    z-index: 4;
    resize: both;
    overflow: auto;
    border-radius: 15px;
    -moz-border-radius: 15px;
    padding-top: 20px;
    box-sizing: border-box;
}

.note-header {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 15px;
    background-color: #ff99aa;
    cursor: move;
    z-index: 10;
    border-radius: 15px 15px 0 0;
}

.note-content {
    padding: 0 10px;
    text-align: center;
}
JavaScript(修复结构+添加拖拽功能)
const addButton = document.getElementById("button");
addButton.addEventListener("click", createNote);

function createNote() {
    const content = prompt("输入笔记内容");
    if (!content) return;

    // 创建容器
    const noteContainer = document.createElement('div');
    noteContainer.className = "note-container";
    // 随机位置避免重叠
    noteContainer.style.left = `${Math.random() * (window.innerWidth - 200)}px`;
    noteContainer.style.top = `${Math.random() * (window.innerHeight - 200)}px`;

    // 创建拖拽头部
    const noteHeader = document.createElement('div');
    noteHeader.className = "note-header";

    // 创建内容区域
    const noteContent = document.createElement('div');
    noteContent.className = "note-content";
    noteContent.textContent = content;

    // 组装元素
    noteContainer.appendChild(noteHeader);
    noteContainer.appendChild(noteContent);
    document.body.appendChild(noteContainer);

    // 绑定拖拽事件
    initDrag(noteHeader, noteContainer);
}

// 实现拖拽功能
function initDrag(header, container) {
    let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;

    header.onmousedown = dragMouseDown;

    function dragMouseDown(e) {
        e.preventDefault();
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        document.onmousemove = elementDrag;
    }

    function elementDrag(e) {
        e.preventDefault();
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        container.style.top = `${container.offsetTop - pos2}px`;
        container.style.left = `${container.offsetLeft - pos1}px`;
    }

    function closeDragElement() {
        document.onmouseup = null;
        document.onmousemove = null;
    }
}

内容的提问来源于stack exchange,提问作者S Pro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:01:21