控制切换状态

Controlling Toggled States

我有一个奇怪的问题。

我创建了两个稍微重叠的正方形。当您单击一个正方形时,它的宽度会通过切换扩展。我想做的是创建一个函数来监视事件是否已被触发,如果是,则将第二个元素的 z-index 更改为高于第一个元素。这可能吗?

JS Fiddle: https://jsfiddle.net/theodore_steiner/qvc7da0s/9/

<div id="square1"></div>
<div id="square2"></div>

CSS:

#square1
{
height: 20px;
width: 20px;
background-color: blue;
position: absolute;
z-index: 3;
transition: all .4s ease;
 }

 #square1.active
 {
 width: 50px;
 }


#square2
{
height: 20px;
width: 20px;
background-color: green;
position: absolute;
z-index: 2;
left: 25px;
 }

JS;

var square1 = document.getElementById("square1");
var square2 = document.getElementById("square2");


square1.onclick = function pushLeft()
    {
    this.classList.toggle("active");
    };

添加此 CSS 规则,该规则使用 general sibling selector ~.

如果可能只想要直系兄弟姐妹,请使用 adjacent sibling selectors +

#square1.active ~ #square2
{
  z-index: 5;
}

示例片段

var square1 = document.getElementById("square1");
var square2 = document.getElementById("square2");

square1.onclick = function pushLeft() {
  this.classList.toggle("active");
};
#square1 {
  height: 20px;
  width: 20px;
  background-color: blue;
  position: absolute;
  z-index: 3;
  transition: all .4s ease;
}
#square1.active {
  width: 50px;
}
#square1.active ~ #square2 {
  z-index: 5;
}
#square2 {
  height: 20px;
  width: 20px;
  background-color: green;
  position: absolute;
  z-index: 2;
  left: 25px;
}
<div id="square1"></div>
<div id="square2"></div>