堆叠DOM元素点击置顶z-index异常修复及代码重构咨询
Bug 原因分析
- 核心问题:原有z-index计算逻辑是基于元素在初始DOM序列中的前置兄弟节点数量,没有考虑已经被点击过的元素已经被赋予了更高的z-index值。比如先点击最后一个元素,它的z-index会被设为12,再点击倒数第二个元素,计算出来的z-index是11,比12低,就会被前一个点击的元素覆盖,出现z-index偏低的问题。
- 次要问题:HTML存在重复ID不符合规范,JS中重复设置
position: relative属于冗余操作。
修复&优化方案
- 新增全局z-index计数器,每次点击元素时先自增再赋值,保证最新点击的元素永远拥有最高的层级
- 用更简洁的API获取元素在父容器中的索引,替代手动遍历兄弟节点的逻辑
- 将固定样式
position: relative下沉到CSS中,减少JS重复操作 - 修正HTML重复ID问题
- 用
event.currentTarget替代event.target,避免元素内部有子节点时触发逻辑异常
修复后的CSS代码
.box { width: 300px; height: 45px; margin: auto; position: relative; /* 固定定位样式移到CSS统一管理 */ } section { margin-top: 50px; } div { transition: transform .75s linear; } #box1 { background: red; } #box2 { background: blue; } #box3 { background: green; } #box4 { background: orange; } #box5 { background: purple; } #box6 { background: teal; } #box7 { background: red; } #box8 { background: blue; } #box9 { background: green; } #box10 { background: orange; } #box11 { background: purple; } #box12 { background: teal; }
修复后的HTML代码
<section> <div class="box" id="box1">1</div> <div class="box" id="box2">2</div> <div class="box" id="box3">3</div> <div class="box" id="box4">4</div> <div class="box" id="box5">5</div> <div class="box" id="box6">6</div> <div class="box" id="box7">7</div> <div class="box" id="box8">8</div> <div class="box" id="box9">9</div> <div class="box" id="box10">10</div> <div class="box" id="box11">11</div> <div class="box" id="box12">12</div> </section>
修复后的JS代码
const divs = document.querySelectorAll("div.box"); let maxZIndex = 0; // 全局维护最高z-index值 divs.forEach((div) => { div.addEventListener("click", (event) => { const target = event.currentTarget; // 获取当前元素在父容器中的索引 const curIndex = Array.from(target.parentElement.children).indexOf(target); // z-index自增保证最新点击的元素层级最高 maxZIndex += 1; target.style.cssText = ` z-index: ${maxZIndex}; transform: translateY(-${curIndex * 45}px); `; }) })
内容的提问来源于stack exchange,提问作者binny
相关产品推荐
相关产品推荐

