2017-07-14 82 views
0

下面的代碼可以讓我改變任何同級div元素的CSS時複選框被選中: -CSS變化:檢查僞類

input[type="radio"]:checked ~ div{ 
    display:none; 
} 

我需要做什麼當列表中的特定單選按鈕被選中時,通過它的Id或它的類來定位特定的div。

我想試試這個純粹的CSS。

伊夫試圖這樣做: -

input[type="radio"]:checked ~ #one.div{ 
display:none; 
} 

https://codepen.io/dyk3r5/pen/WOmxpV?editors=1111

<div class="container"> 


    <input type="radio" id="opt1" name="radiolist" checked> 
    <label for='opt1'>New Account</label> 


    <input type="radio" id="opt2" name="radiolist"> 
    <label for='opt2'>Existing Account</label> 

    <div id="one">Lorem Ipsum 1</div> 
    <div id="two">Lorem Ipsum 2</div> 

</div> 

html, body{ 
    height :100%; 
} 

.container{ 

    display:flex; 
    justify-content:center; 
} 

label{ 
    color:#000; 
    font-weight:600; 

    height: 25px; 
    padding: 5px 10px; 
    border-bottom: 2px solid lightgrey; 
    margin: 5px 1px; 

} 

input[type="radio"]{ 
    display:none; 
} 

input[type="radio"]:checked + label{ 
    border-bottom: 2px solid red; 
} 

input[type="radio"]:checked ~ div{ 
display:none; 
} 

回答

1

我更新的CSS當選擇一定的單選按鈕,以顯示相應的div。問題是你的選擇器的div:#one.div。這針對id爲「one」和class「div」的元素。應該是div#one

html, 
 
body { 
 
    height: 100%; 
 
} 
 

 
.container { 
 
    display: flex; 
 
    justify-content: center; 
 
} 
 

 
label { 
 
    color: #000; 
 
    font-weight: 600; 
 
    height: 25px; 
 
    padding: 5px 10px; 
 
    border-bottom: 2px solid lightgrey; 
 
    margin: 5px 1px; 
 
} 
 

 
input[type="radio"] { 
 
    display: none; 
 
} 
 

 
input[type="radio"]:checked+label { 
 
    border-bottom: 2px solid red; 
 
} 
 

 
input[type="radio"]~div { 
 
    display: none; 
 
} 
 

 
input[type="radio"][id="opt1"]:checked~div#one, 
 
input[type="radio"][id="opt2"]:checked~div#two { 
 
    display: block; 
 
}
<div class="container"> 
 

 

 
    <input type="radio" id="opt1" name="radiolist" checked> 
 
    <label for='opt1'>New Account</label> 
 

 

 
    <input type="radio" id="opt2" name="radiolist"> 
 
    <label for='opt2'>Existing Account</label> 
 

 
    <div id="one">Lorem Ipsum 1</div> 
 
    <div id="two">Lorem Ipsum 2</div> 
 

 
</div>

+0

這是輝煌的,謝謝。如果你想在

以外的目標div元素會是可能的? – Derek

+1

CSS選擇器只能在一個方向上進入DOM(即兄弟姐妹或兒童)。因此,如果您想要定位DOM(即父代或祖先)以上的東西,則必須使用JS。 – sorayadragon

+0

感謝您的幫助! – Derek