控制切换状态

时间:2016-06-09 17:54:46

标签: javascript html css toggle

我有一个奇怪的问题。

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

JS小提琴: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");
    };

1 个答案:

答案 0 :(得分:2)

添加此CSS规则,该规则使用split

如果可能只想要直接兄弟,请使用general sibling selector ~

#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>