使用Vanilla JavaScript移动嵌套HTML DOM节点的问题
问题描述
现有如下DOM结构:
<div class='row'> <div class='cell'> <div class='item'>1</div> <div class='item'>2</div> </div> <div class='cell'> <div class='item'>3</div> </div> </div> <div class='row'> <div class='cell'> <div class='item'>4</div> <div class='item'>5</div> </div> <div class='cell'> <div class='item'>6</div> <div class='item'>7</div> </div> </div>
配套CSS代码:
.row { display: flex; flex-wrap: wrap; } .cell {} .item { background-color: #1d8ed2; height: 100px; width: 200px; margin-left: 10px; margin-bottom: 10px; }
当前渲染效果:
![实际效果]
需要实现的逻辑是:将同一行内元素数量不足2个的cell,从该行下一个cell中移动一个item过来,最终达到如下渲染效果:
![预期效果]
现有尝试的JS代码无法得到预期结果:
const cells = document.querySelectorAll('.cell'); if (cells.length > 0) { cells.forEach((cell, index) => { if (cell.children.length == 2) { return; } if (cells[index + 1]) { const itemToMove = cells[index + 1].children[0]; cell.appendChild(itemToMove); } }) }
当前代码的错误效果:
![非预期效果]
问题分析
现有代码的核心问题是没有按行分组处理,直接遍历了所有cell,导致会跨row移动元素(比如把第二行的元素移到第一行的cell中),不符合需求。
解决方案
需要按每个row单独处理,确保元素只在同一行内移动:
// 遍历每一行,确保操作只在当前行内进行 document.querySelectorAll('.row').forEach(row => { // 将当前行的cell转为数组,方便顺序遍历操作 const cells = Array.from(row.querySelectorAll('.cell')); // 遍历当前行的每个cell for (let i = 0; i < cells.length; i++) { const currentCell = cells[i]; // 如果当前cell已有2个item,跳过 if (currentCell.children.length >= 2) continue; // 从当前cell的下一个位置开始,找有多余item的cell let nextCellIndex = i + 1; while (nextCellIndex < cells.length) { const nextCell = cells[nextCellIndex]; if (nextCell.children.length > 0) { // 移动nextCell的第一个item到当前cell currentCell.appendChild(nextCell.children[0]); // 移动后若当前cell已满足2个item,停止寻找 if (currentCell.children.length === 2) break; } nextCellIndex++; } } });
内容的提问来源于stack exchange,提问作者turkehy
相关产品推荐
相关产品推荐

