控制切换状态
问题描述:
我有一个奇怪的问题。控制切换状态
我创建了两个略有重叠的方块。当您单击一个正方形时,其宽度将通过切换延伸。我想要做的是创建一个函数,监视事件是否已被触发,如果是,则将第二个元素的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");
};
答
添加此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>
所以行#square1.active〜#square2的 “〜” 基本上说,如果square1是积极做这方2?另外,一般情况下,JS中有一个方法方法来检查事件是否被触发? –
@TheodoreSteiner是的,使用[兄弟选择器'〜'](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors) – LGSon
@TheodoreSteiner如何检查一个事件是否被触发? ...你的'onclick'事件就是这样,当它被解雇时,它告诉你有人被点击。 – LGSon