根据您要支持的浏览器,除了隐藏单选按钮之外,还可以使用
:checked pseudo-class选择器。
使用此HTML:
>On
>
>Off
你可以使用像下面的CSS:
input[type="radio"].toggle {
display: none;
}
input[type="radio"].toggle:checked + label {
/* Do something special with the selected state */
}
例如,如果您使用的是Bootstrap,您可以将class =“btn”添加到您的< label>元素并适当地对其进行设置,以创建类似以下内容的切换:
…只需要以下额外的CSS:
input[type="radio"].toggle:checked + label {
background-image: linear-gradient(to top,#969696,#727272);
box-shadow: inset 0 1px 6px rgba(41, 41, 41, 0.2),
0 1px 2px rgba(0, 0, 0, 0.05);
cursor: default;
color: #E6E6E6;
border-color: transparent;
text-shadow: 0 1px 1px rgba(40, 40, 40, 0.75);
}
input[type="radio"].toggle + label {
width: 3em;
}
input[type="radio"].toggle:checked + label.btn:hover {
background-color: inherit;
background-position: 0 0;
transition: none;
}
input[type="radio"].toggle-left + label {
border-right: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
input[type="radio"].toggle-right + label {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
我已经包括这个以及额外的备用样式在radio button toggle jsFiddle demo.注意:checked仅支持在IE 9,所以这种方法只限于较新的浏览器。
但是,如果你需要支持IE 8并愿意回退JavaScript *,你可以在伪支持中检查:检查没有太多的困难(虽然你可以很容易地直接在标签上设置类) 。
$('.no-checkedselector').on('change', 'input[type="radio"].toggle', function () {
if (this.checked) {
$('input[name="' + this.name + '"].checked').removeClass('checked');
$(this).addClass('checked');
// Force IE 8 to update the sibling selector immediately by
// toggling a class on a parent element
$('.toggle-container').addClass('xyz').removeClass('xyz');
}
});
$('.no-checkedselector input[type="radio"].toggle:checked').addClass('checked');
然后,您可以对CSS进行一些更改以完成以下操作:
input[type="radio"].toggle {
/* IE 8 doesn't seem to like to update radio buttons that are display:none */
position: absolute;
left: -99em;
}
input[type="radio"].toggle:checked + label,
input[type="radio"].toggle.checked + label {
/* Do something special with the selected state */
}
*如果您使用Modernizr,您可以使用:selector test来帮助确定是否需要回退。我在示例代码中调用我的测试“checkedselector”,随后只有在测试失败时才设置jQuery事件处理程序。