2016-06-09 101 views
0

我有一個奇怪的問題。控制切換狀態

我創建了兩個略有重疊的方塊。當您單擊一個正方形時,其寬度將通過切換延伸。我想要做的是創建一個函數,監視事件是否已被觸發,如果是,則將第二個元素的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"); 
    }; 

回答

2

添加此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>

+0

所以行#square1.active〜#square2的 「〜」 基本上說,如果square1是積極做這方2?另外,一般情況下,JS中有一個方法方法來檢查事件是否被觸發? –

+0

@TheodoreSteiner是的,使用[兄弟選擇器'〜'](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors) – LGSon

+0

@TheodoreSteiner如何檢查一個事件是否被觸發? ...你的'onclick'事件就是這樣,當它被解僱時,它告訴你有人被點擊。 – LGSon