根据您想要支持的浏览器,您可以使用:checked伪类 http://www.w3.org/TR/css3-selectors/#checked除了隐藏单选按钮之外,还可以使用选择器。
使用这个 HTML:
<input type="radio" id="toggle-on" name="toggle" checked
><label for="toggle-on">On</label
><input type="radio" id="toggle-off" name="toggle"
><label for="toggle-off">Off</label>
您可以使用类似以下 CSS 的内容:
input[type="radio"].toggle {
display: none;
}
input[type="radio"].toggle:checked + label {
/* Do something special with the selected state */
}
例如,(为了保持自定义 CSS 的简洁)如果您使用引导程序 http://twitter.github.com/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;
}
我已将其以及额外的后备样式包含在单选按钮切换 jsFiddle 演示 http://jsfiddle.net/tms/uPv6X/。注意:checked
仅 IE 9 支持,因此此方法仅限于较新的浏览器。
但是,如果您需要支持 IE 8 并且愿意依赖 JavaScript*,您可以破解对 IE 8 的伪支持:checked
没有太多困难(尽管此时您可以直接在标签上轻松设置类别)。
使用一些快速而肮脏的 jQuery 代码作为解决方法的示例 http://jsfiddle.net/tms/DBZPh/:
$('.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 */
}
*If you're using Modernizr, you can use the :selector test https://gist.github.com/paulirish/441842 to help determine if you need the fallback. I called my test "checkedselector" in the example code, and the jQuery event handler is subsequently only set up when the test fails.