检查无线电时如何更改元素的状态?

时间:2019-02-24 13:25:25

标签: html5 css3

我有一个使用Django模板语言呈现的表单。 我想做的是在选中时使各个单选按钮的标签不透明。问题是我似乎无法正确定位标签。我在CSS中使用“ #id_type input [type = radio]:checked〜#id_type标签”行尝试了多种不同的变体。发布的只是最新的,没有用。如果有人能指出这个问题,那就太好了。谢谢。

# HTML (actual code)

<form class="form1" action="" method="post" novalidate>
...
{% for field in form %}
{% if field is form.type %}

  <div class="paymentRadio">
    {% render_field field placeholder=field.label %}
  </div>

  {% else %}
  ...

# HTML (inspect element)
<div class="paymentRadio">
  <ul id="id_0-type">

    <li><label for="id_0-type_0"><input type="radio" name="0-type" value="Label1" placeholder="Type" required="" id="id_0-type_0">
      Label1</label>
    </li>

    <li><label for="id_0-type_1"><input type="radio" name="0-type" value="Label2" placeholder="Type" required="" id="id_0-type_1">
      Label2</label>
    </li>

  </ul>
</div>

# CSS

#id_0-type {
    display: inline-block;
    height: auto;
    width: auto;
    font-family: helvetica;
    font-size: 1.75rem;
    transition: border-color .25s ease, box-shadow .25s ease;
    position: relative;
    margin: 0 auto;
    float: left;
}

#id_0-type input[type=radio] {
  position: absolute;
  visibility: hidden;
}

#id_0-type label {
  height: auto;
  font-weight: normal;
  font-size: 2rem;
  color: $white;
  background: $black;
  text-align: center;
  top: .5rem;
  position: relative;
  margin: 0 auto;
  padding: 1rem;
  display: block;
  z-index: 2;
  cursor: pointer;
  -webkit-transition: all 0.25s linear;
  opacity: .5;
&:hover{
  opacity: 1;
}}

# THIS SEEMS TO BE THE PROBLEM 

#id_0-type input[type=radio]:checked ~ #id_type label {
  opacity: 1;
}

1 个答案:

答案 0 :(得分:1)

您的HTML中存在问题。您输入的内容在标签内,并且您正在尝试为作为父标签的标签设置样式。 CSS不允许我们设置父样式。我已经将输入与标签分离并修复了。

#id_0-type {
  display: inline-block;
  height: auto;
  width: auto;
  font-family: helvetica;
  font-size: 1.75rem;
  transition: border-color .25s ease, box-shadow .25s ease;
  position: relative;
  margin: 0 auto;
  float: left;
}

#id_0-type input[type=radio] {
  position: absolute;
  visibility: hidden;
}

#id_0-type label {
  height: auto;
  font-weight: normal;
  font-size: 2rem;
  color: white;
  background: black;
  text-align: center;
  top: .5rem;
  position: relative;
  margin: 0 auto;
  padding: 1rem;
  display: block;
  z-index: 2;
  cursor: pointer;
  -webkit-transition: all 0.25s linear;
  opacity: .5;
}

#id_0-type label:hover {
  opacity: 1;
}

#id_0-type input[type=radio]:checked ~ label {
  opacity: 1;
}
<div class="paymentRadio">
  <ul id="id_0-type">

    <li>
      <input type="radio" name="0-type" value="Label1" placeholder="Type" required="" id="id_0-type_0">
      <label for="id_0-type_0">
      Label1</label>
    </li>

    <li>
      <input type="radio" name="0-type" value="Label2" placeholder="Type" required="" id="id_0-type_1"><label for="id_0-type_1">
      Label2</label>
    </li>

  </ul>
</div>