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

如何用单个脚本修改两个盒子的z-index属性?

解决单个按钮修改两个盒子z-index的问题

直接在你的myFunction函数里添加修改第二个盒子z-index的代码即可,一次操作多个元素样式完全可行,不需要复杂方法。

固定设置z-index值的方案

修改后的JavaScript代码:

function myFunction() {
  // 修改DIV1的层级
  document.getElementById("DIV1").style.zIndex = "-1";
  // 同时修改DIV2的层级,数值可根据需求调整
  document.getElementById("DIV2").style.zIndex = "1";
}

切换两个盒子层级的方案(点击一次交换上下层)

如果需要点击按钮时交换两个盒子的层级,可以用以下逻辑:

function myFunction() {
  const div1 = document.getElementById("DIV1");
  const div2 = document.getElementById("DIV2");
  
  // 获取当前层级,未设置时默认取"0"
  const div1ZIndex = div1.style.zIndex || "0";
  const div2ZIndex = div2.style.zIndex || "0";
  
  // 交换两者的z-index
  div1.style.zIndex = div2ZIndex;
  div2.style.zIndex = div1ZIndex;
}

完整代码示例(以固定设置数值为例)

HTML

<button onclick="myFunction()">Enter</button>

<div id="DIV1">
  <h1>Gone fishing</h1>
</div>

<div id="DIV2">
  <h1>Gone fishing</h1>
</div>

CSS

#DIV1 {
  position: absolute;
  width: 200px;
  height: 100px;
  background-color: lightblue;
  border: 1px solid black;
}
#DIV2 {
  position: relative;
  top: 70px;
  left: 30px;
  width: 200px;
  height: 100px;
  background-color: coral;
  border: 1px solid black;
}

JavaScript

function myFunction() {
  document.getElementById("DIV1").style.zIndex = "-1";
  document.getElementById("DIV2").style.zIndex = "1";
}

点击按钮后,两个盒子的z-index会同时被修改,核心就是在同一个函数中执行多条DOM样式修改语句。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:40:26