如何使(自定义)单选按钮在CSS3中工作

时间:2014-03-06 22:25:44

标签: html5 css3

我一直在尝试使自定义单选按钮工作。我一直在使用复选框,但发现我需要将选中的选项限制为一个。我一直在寻找使用Google发现的示例/教程,并且我认为我已经足够了解一组简单的4个单选按钮但是...

它们最初在选中第一个按钮后正确显示,但检查其他按钮只显示选中的PNG:先前选中的按钮不会恢复为未选中状态。

按钮按顺序水平排列在自己的div中。

HTML

<div class='radio'>
  <input id='B12' type='radio' class='radiobutton' checked>
    <label id='lblB12' class='radiobutton-label' for='B12'>IR&nbsp;</label>
  <input id='BBW' type='radio' class='radiobutton' >
    <label id='lblBBW' class='radiobutton-label' for='BBW'>Wide</label>
  <input id='B10' type='radio' class='radiobutton' >
    <label id='lblB10' class='radiobutton-label' for='B10'>B10</label>
  <input id='B8' type='radio' class='radiobutton' >
    <label id='lblB8' class='radiobutton-label' for='B8'>B8&nbsp;</label>
</div>

CSS3

.radiobutton-label {  
  display: inline-block;  
  cursor: pointer;  
  position: relative;  
  padding-left: 25px;  
  margin-right: 15px;  
  font-size: 15px;  
}  

input[type="radio"] {
  display: none;
  margin: 10px;
}

.radiobutton-label:before {  
  content:"";
  display: inline-block;  
  width: 24px;      
  height: 24px;  
  margin-right: 10px;  
  position: absolute;  
  left: 0;  
  bottombottom: 1px;
  background: url(resources/CheckBoxUnchecked.png) left top; 
}  

input[type=radio]: + label:before {  
  background: url(resources/CheckBoxUnchecked.png) left top;
}  

input[type=radio]:checked + label:before {  
  background: url(resources/CheckBoxOK.png) left top;
}  

这是我尝试过的第一个网页。

1 个答案:

答案 0 :(得分:4)

  

Relevant Spec - 17 Forms / 17.2.1 Control types

     

单选按钮就像复选框一样,只有当多个共享相同的控件名称时,它们是互斥的:当一个按钮被“打开”时,所有其他具有相同名称的按钮都会被“关闭”。

因此,如果您希望无线电元素互斥,只需为它们提供相同的name属性即可。在这种情况下,我只使用了name="checkboxes"

更新了HTML EXAMPLE HERE

<div class='radio'>
    <input id='B12' type='radio' class='radiobutton' name="checkboxes" checked="checked"/>
    <label id='lblB12' class='radiobutton-label' for='B12'>IR&nbsp;</label>
      <input id='BBW' type='radio' class='radiobutton' name="checkboxes"/>
    <label id='lblBBW' class='radiobutton-label' for='BBW'>Wide</label>
      <input id='B10' type='radio' class='radiobutton' name="checkboxes"/>
    <label id='lblB10' class='radiobutton-label' for='B10'>B10</label>
      <input id='B8' type='radio' class='radiobutton' name="checkboxes"/>
    <label id='lblB8' class='radiobutton-label' for='B8'>B8&nbsp;</label>
</div>

基本CSS:

input[type=radio] + label:before {  
  background: url('http://www.csscheckbox.com/checkboxes/vlad.png') 2px 4px no-repeat;
}  

input[type=radio]:checked + label:before {  
  background: url('http://www.csscheckbox.com/checkboxes/vlad.png') 2px -18px no-repeat;
}