隐藏元素如果单选按钮被选中?

huangapple go评论81阅读模式
英文:

How to hide an element if radio button is checked?

问题

要隐藏div块,只有在单选按钮one被选中时,可以使用以下CSS代码,不需要使用其他语言:

  1. #one:checked + label + #mainDiv {
  2. display: none;
  3. }

这段CSS代码将隐藏id为"mainDiv"的div,但仅在id为"one"的单选按钮被选中时。

英文:

Say I have Radio Buttons and a Div.

  1. <input id="one" type="radio" value="1">
  2. <label>One</label>
  3. <input id="two" type="radio" value="2">
  4. <label>Two</label>
  5. <div id="mainDiv">
  6. <p>Hello</p>
  7. </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属性与~组合符一起使用:

  1. #one:checked ~ #mainDiv {
  2. display: none;
  3. }

此外,你可以查看MDN文档中的示例Toggling elements with a hidden checkbox

英文:

You can use the checked property of the one radio button together with the ~ combinator:

  1. #one:checked ~ #mainDiv {
  2. display: none;
  3. }

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

  1. &lt;!DOCTYPE html&gt;
  2. &lt;html&gt;
  3. &lt;head&gt;
  4. &lt;style&gt;
  5. #one:checked ~ #mainDiv {
  6. display: none;
  7. }
  8. &lt;/style&gt;
  9. &lt;/head&gt;
  10. &lt;body&gt;
  11. &lt;input id=&quot;one&quot; type=&quot;radio&quot; name=&quot;myRadioGroup&quot; value=&quot;1&quot;&gt;
  12. &lt;label for=&quot;one&quot;&gt;One&lt;/label&gt;
  13. &lt;input id=&quot;two&quot; type=&quot;radio&quot; name=&quot;myRadioGroup&quot; value=&quot;2&quot;&gt;
  14. &lt;label for=&quot;two&quot;&gt;Two&lt;/label&gt;
  15. &lt;div id=&quot;mainDiv&quot;&gt;
  16. &lt;p&gt;Hello&lt;/p&gt;
  17. &lt;/div&gt;
  18. &lt;/body&gt;
  19. &lt;/html&gt;

<!-- end snippet -->

Also, you can check the example from documentation MDN Toggling elements with a hidden checkbox

huangapple
  • 本文由 发表于 2023年5月20日 21:40:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定