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

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

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 -->

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;style&gt;
    #one:checked ~ #mainDiv {
      display: none;
    }
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;input id=&quot;one&quot; type=&quot;radio&quot; name=&quot;myRadioGroup&quot; value=&quot;1&quot;&gt;
  &lt;label for=&quot;one&quot;&gt;One&lt;/label&gt;
  &lt;input id=&quot;two&quot; type=&quot;radio&quot; name=&quot;myRadioGroup&quot; value=&quot;2&quot;&gt;
  &lt;label for=&quot;two&quot;&gt;Two&lt;/label&gt;

  &lt;div id=&quot;mainDiv&quot;&gt;
    &lt;p&gt;Hello&lt;/p&gt;
  &lt;/div&gt;
&lt;/body&gt;
&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:

确定