如何用JavaScript在HTML中添加嵌套Div?笔记应用嵌套Div异常排查
问题修复方案
核心问题分析
- 重复ID冲突:每次生成的容器和头部都用相同ID,HTML中ID必须唯一,导致后续生成的元素无法正确应用CSS样式。
- 文本层级重叠:父容器直接设置
textContent,子div插入后会和父容器文本重叠,导致子div显示异常。 - 拖拽逻辑缺失:仅设置了拖拽光标样式,没有实现实际的拖拽交互功能。
修正后代码
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
相关产品推荐
相关产品推荐

