单选按钮选中选项

时间:2016-07-20 06:42:22

标签: html html5 css3 radio-button

我正在处理单选按钮,我已经设计了谷歌帮助的东西但是在这个fiddle中你会看到在页面加载时都检查了两个,我只使用了带有radio1按钮的选中选项。我需要更改页面加载radio1button被检查,并且不检查radio2按钮。

当你点击第二个按钮时,你会看到按钮1将被取消选中,但按钮2仍然被选中,任何解决方案?

<input type="radio" name="radio" id="radio1" class="radio" checked/>
<label for="radio1">Now</label>



<input type="radio" name="radio" id="radio2" class="radio"/>
<label for="radio2">Later</label>

<style>
label {
  width: 150px;
  border-radius: 3px;
  border: 1px solid #D1D3D4
}

/* hide input */
input.radio:empty {
margin-left: -999px;
}

/* style label */
input.radio:empty ~ label {
position: relative;
float: left;
line-height: 2.5em;
text-indent: 3.25em;
margin-top: 2em;
margin-left: 2em;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

input.radio:empty ~ label:before {
position: absolute;
display: block;
top: 0;
bottom: 0;
left: 0;
content: '';
width: 2.5em;
background: #D1D3D4;
border-radius: 3px 0 0 3px;
}

/* toggle hover */
input.radio:hover:not(:checked) ~ label:before {
content:'\2714';
text-indent: .9em;
color: #C2C2C2;
}

input.radio:hover:not(:checked) ~ label {
color: #888;
}

/* toggle on */
input.radio:checked ~ label:before {
content:'\2714';
text-indent: .9em;
color: #9CE2AE;
background-color: #4DCB6D;
}

input.radio:checked ~ label {
color: #777;
}

/* radio focus */
input.radio:focus ~ label:before {
box-shadow: 0 0 0 3px #999;
}

</style>

1 个答案:

答案 0 :(得分:1)

而不是一般的兄弟~使用相邻的兄弟+选择器

普通兄弟会选择元素旁边的所有标签

相邻的兄弟会只选择下一个标签

https://jsfiddle.net/victor_007/8ax050s8/1/

&#13;
&#13;
label {
  width: 150px;
  border-radius: 3px;
  border: 1px solid #D1D3D4
}
/* hide input */

input.radio:empty {
  margin-left: -999px;
}
/* style label */

input.radio:empty + label {
  position: relative;
  float: left;
  line-height: 2.5em;
  text-indent: 3.25em;
  margin-top: 2em;
  margin-left: 2em;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
input.radio:empty + label:before {
  position: absolute;
  display: block;
  top: 0;
  bottom: 0;
  left: 0;
  content: '';
  width: 2.5em;
  background: #D1D3D4;
  border-radius: 3px 0 0 3px;
}
/* toggle hover */

input.radio:hover:not(:checked) + label:before {
  content: '\2714';
  text-indent: .9em;
  color: #C2C2C2;
}
input.radio:hover:not(:checked) + label {
  color: #888;
}
/* toggle on */

input.radio:checked + label:before {
  content: '\2714';
  text-indent: .9em;
  color: #9CE2AE;
  background-color: #4DCB6D;
}
input.radio:checked + label {
  color: #777;
}
/* radio focus */

input.radio:focus + label:before {
  box-shadow: 0 0 0 3px #999;
}
&#13;
<input type="radio" name="radio" id="radio1" class="radio" checked/>
<label for="radio1">Now</label>

<input type="radio" name="radio" id="radio2" class="radio" />
<label for="radio2">Later</label>
&#13;
&#13;
&#13;