如何添加闭合</div>?MaterializeCSS网格布局DOM操作问题
解决MaterializeCSS网格中插入整行内容的布局问题
首先得明确:你不能直接通过插入</div>字符串来闭合DOM元素——DOM是节点树结构,不是HTML文本,这种字符串操作只会生成无效节点,根本不会被浏览器正确解析。这就是你之前尝试失败的核心原因。
我们需要通过标准DOM节点操作来实现需求:当点击指定列时,先把当前row中该列之后的元素临时移走,然后在当前row后面插入一个新的全屏row(s12类),最后把移走的元素放到新row里维持布局完整性。
具体实现步骤(jQuery版本)
$('#clicky').on('click', function() { // 1. 定位目标列和它的父级row const targetCol = $(this).closest('[data-index-value="2"]'); const currentRow = targetCol.parent('.row'); // 2. 把目标列之后的所有列从当前row中移出并暂存 const remainingCols = targetCol.nextAll('.col'); // 3. 创建新的信息展示row(s12占满整行) const infoRow = $('<div class="row"></div>'); const infoCol = $('<div class="col s12"></div>').html('<p>More information section</p>'); infoRow.append(infoCol); // 4. 将信息row插入到当前row的后方 infoRow.insertAfter(currentRow); // 5. 如果有剩余列,创建新row容纳它们并放到信息row后面 if (remainingCols.length > 0) { const newRow = $('<div class="row"></div>').append(remainingCols); newRow.insertAfter(infoRow); } });
为什么这么做?
- 完全基于DOM节点操作,避免了字符串拼接的无效操作
- 严格遵循Materialize网格的结构规则:每个row包含若干col,不会出现未闭合标签或结构混乱
- 专门处理了目标列不是当前row最后一列的情况(这就是你点击前几列布局错乱的根源),把剩余列转移到新row,保证网格布局的正确性
原生JS版本(无需jQuery)
document.getElementById('clicky').addEventListener('click', function() { const targetCol = this.closest('[data-index-value="2"]'); const currentRow = targetCol.parentElement; // 收集目标列之后的所有col节点 const remainingCols = []; let nextSibling = targetCol.nextElementSibling; while (nextSibling) { if (nextSibling.classList.contains('col')) { remainingCols.push(nextSibling); currentRow.removeChild(nextSibling); } nextSibling = targetCol.nextElementSibling; } // 创建信息row和对应的s12列 const infoRow = document.createElement('div'); infoRow.classList.add('row'); const infoCol = document.createElement('div'); infoCol.classList.add('col', 's12'); infoCol.innerHTML = '<p>More information section</p>'; infoRow.appendChild(infoCol); // 插入信息row到DOM中 currentRow.parentNode.insertBefore(infoRow, currentRow.nextSibling); // 处理剩余列,维持布局 if (remainingCols.length > 0) { const newRow = document.createElement('div'); newRow.classList.add('row'); remainingCols.forEach(col => newRow.appendChild(col)); infoRow.parentNode.insertBefore(newRow, infoRow.nextSibling); } });
效果说明
- 点击按钮后,目标列所在的row会保留目标列(以及它之前的列)
- 紧接着出现一个占满整行的s12列,展示你的信息内容
- 原当前row中目标列之后的所有列,会被放到新的row里,紧接在信息row后方,完全符合Materialize的网格布局逻辑
内容的提问来源于stack exchange,提问作者JimDigiJim
相关产品推荐
相关产品推荐

