复选框的CSS样式 [英] CSS Style for Checkboxes
问题描述
是否可以在不使用javascript的情况下为HTML复选框设置样式?
此代码示例将与IE正常工作,但不是在Firefox或Chrome。
http://jsfiddle.net/5wJxF/
任何建议?
Is it possible to style the HTML checkbox without using javascripts? This code for example will work fine with IE, but not on Firefox or Chrome. http://jsfiddle.net/5wJxF/ Any suggestions?
推荐答案
是的。
您不能直接为checkbox元素设定样式,但如果您使用
You can't directly style the checkbox element, but the effect you're looking for can be achieved if you use a <label>
element in conjunction with the checkbox, and style that.
<input type="checkbox" id="field1" class="mycheckbox" />
<label for="field1" class="mycheckbox-label">Label here</label>
然后你的CSS看起来像这样:
And then your CSS would look like this:
.mycheckbox {
display:none;
}
.mycheckbox + label {
padding:20px; /*or however wide your graphic is*/
background:url(/fancy-unchecked.gif) no-repeat left center;
}
.mycheckbox:checked + label {
background:url(/fancy-checked.gif) no-repeat left center;
}
这是一个工作示例: http://jsfiddle.net/TVaPX/ (使用Firefox 5测试)
Here is a working example: http://jsfiddle.net/TVaPX/ (tested with Firefox 5)
这种方法的麻烦是只适用于现代浏览器。旧版浏览器可能不支持:checked
或 +
CSS选择器。但如果你没有支持旧版本的IE,那么这将工作。以上示例在IE8中不起作用(它支持 +
,但不支持:checked
)。
The trouble with this approach is that it only works in modern browsers. Older browsers may not support the :checked
or +
CSS selectors. But if you're okay with not supporting older versions of IE, then this will work. The example above does not work in IE8 (it supports +
but not :checked
).
如果你不舒服,那么你必须坚持使用Javascript解决方案。
If you're not comfortable with that, then you'll have to stick with a Javascript solution.
但是,与此类似,您仍然可以使用非常少量的Javascript代码:只需要一个单行的JS,当选中复选框的类时,可以使用所有上述代码,但使用替代类名的:checked
选择器。这将在IE7和IE8中工作。
However, with an approach similar to this, you can still do it with very minimal amounts of Javascript code: simply have a one-line JS that toggles the class of the checkbox when it's checked, and you can use all the above code, but with the alternate classname instead of the :checked
selector. That will work in IE7 and IE8.
希望有帮助。
这篇关于复选框的CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!