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

React组件点击时动态调整z-index实现层级切换求助

点击盒子切换层级实现方案

核心逻辑

通过控制元素的z-index属性实现层级切换,维护一个变量追踪当前顶层盒子,点击新盒子时将其设为顶层,同时把原顶层盒子的层级还原。

实现代码

HTML结构

<div class="box red"></div>
<div class="box green"></div>
<div class="box blue"></div>

CSS样式

.box {
  position: absolute;
  width: 200px;
  height: 200px;
  cursor: pointer;
  z-index: 1; /* 初始层级统一为1 */
}

.red {
  top: 50px;
  left: 50px;
  background-color: red;
}

.green {
  top: 100px;
  left: 100px;
  background-color: green;
}

.blue {
  top: 150px;
  left: 150px;
  background-color: blue;
}

JavaScript逻辑

// 追踪当前处于顶层的盒子
let currentTopBox = null;
// 获取所有盒子元素
const boxes = document.querySelectorAll('.box');

boxes.forEach(box => {
  box.addEventListener('click', () => {
    // 若点击的已是顶层盒子,无需操作
    if (box === currentTopBox) return;
    
    // 还原原顶层盒子的层级
    if (currentTopBox) {
      currentTopBox.style.zIndex = 1;
    }
    
    // 将当前点击的盒子设为顶层
    box.style.zIndex = 2;
    // 更新顶层盒子记录
    currentTopBox = box;
  });
});

效果验证

  1. 点击红色盒子:红色盒子z-index变为2,成为顶层
  2. 点击蓝色盒子:蓝色盒子z-index设为2,红色盒子还原为1,此时层级从下到上为绿色(1)→红色(1)→蓝色(2),符合需求

内容的提问来源于stack exchange,提问作者Meto twi8

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:10:39