英文:
How to hide an element if radio button is checked?
问题
要隐藏div块,只有在单选按钮one被选中时,可以使用以下CSS代码,不需要使用其他语言:
#one:checked + label + #mainDiv {
display: none;
}
这段CSS代码将隐藏id为"mainDiv"的div,但仅在id为"one"的单选按钮被选中时。
英文:
Say I have Radio Buttons and a Div.
<input id="one" type="radio" value="1">
<label>One</label>
<input id="two" type="radio" value="2">
<label>Two</label>
<div id="mainDiv">
<p>Hello</p>
</div>
How do I hide the div block only if radiobutton one is checked?
Without using any other language and only css.
I tried to use +
and ~
. I dont know if im using it wrong but it didnt work.
答案1
得分: 1
你可以使用one
单选按钮的checked
属性与~
组合符一起使用:
#one:checked ~ #mainDiv {
display: none;
}
此外,你可以查看MDN文档中的示例Toggling elements with a hidden checkbox。
英文:
You can use the checked
property of the one
radio button together with the ~
combinator:
#one:checked ~ #mainDiv {
display: none;
}
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<head>
<style>
#one:checked ~ #mainDiv {
display: none;
}
</style>
</head>
<body>
<input id="one" type="radio" name="myRadioGroup" value="1">
<label for="one">One</label>
<input id="two" type="radio" name="myRadioGroup" value="2">
<label for="two">Two</label>
<div id="mainDiv">
<p>Hello</p>
</div>
</body>
</html>
<!-- end snippet -->
Also, you can check the example from documentation MDN Toggling elements with a hidden checkbox
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论