jQuery 使用 CSS 的自定义单选和复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6410655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom Radio and Checkbox using CSS
提问by Harsha M V
is there a way to style the radio button and checkbox using custom images. using just CSS ?
有没有办法使用自定义图像来设置单选按钮和复选框的样式。只使用 CSS 吗?
Can some one point me how it can be done ?
有人能指出我怎么做吗?
Else which are the best plugins for jquery to do so ?
还有哪些是 jquery 最好的插件?
回答by Balanivash
回答by TLindig
You can do it with pure css3, using the pseudo class :checked
. Inspired by this articleI got the following solution:
您可以使用伪类,使用纯 css3 来实现:checked
。受这篇文章的启发,我得到了以下解决方案:
Features:
特征:
- only css
- no
id
attribute needed - no z-index needed
- 只有 CSS
- 不需要
id
属性 - 不需要 z-index
Try it on jsfiddle: http://jsfiddle.net/tlindig/n6by8/6/
在 jsfiddle 上试试:http: //jsfiddle.net/tlindig/n6by8/6/
HTML:
HTML:
<label>
<input type="radio" name="rg"/><i></i>
option 1
</label>
<label>
<input type="radio" checked name="rg"/><i></i>
option 2
</label>
<label>
<input type="radio" name="rg"/><i></i>
option 3
</label>
CSS:
CSS:
input[type="radio"] {
display:none;
}
input[type="radio"] + i:before {
content:'18';
color:red;
}
input[type="radio"]:checked + i:before {
content:'13';
color:green;
}
Some explanations:
一些解释:
Element i
is needed to add pseudo element :before
with the icon as content. input
elements are empty tags and can not have pseudo elements like :before
and :after
so we need a extra element. You could also use span
or div
, but i
is shorter.
元素i
需要添加:before
以图标为内容的伪元素。input
元素是空标签,不能有像:before
等:after
这样的伪元素,所以我们需要一个额外的元素。您也可以使用span
或div
,但i
较短。
label
is needed to trigger the input
. If you wrap the input
with a label
element, you do not need id
and for
attributes for association.
label
需要触发input
. 如果input
用label
元素包裹,则不需要id
和for
属性进行关联。
'\2718' and '\2713' are UTF8 character codes for "ballot X" and "check mark".
'\2718' 和 '\2713' 是“选票 X”和“复选标记”的 UTF8 字符代码。
Instead of content
you could also set a background-image
or what ever you like.
而不是content
你也可以设置一个background-image
或你喜欢的任何东西。
It works in all modern browsers and ie9+.
它适用于所有现代浏览器和 ie9+。
回答by Digbyswift
jQuery UI has some excellent and easily implementable options:
jQuery UI 有一些优秀且易于实现的选项:
回答by Alex
Not sure you'll be able to do this with pure CSS, but this way is great way with javascript:
不确定你能不能用纯 CSS 做到这一点,但这种方式对 javascript 来说是个好方法:
http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/
http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/
回答by Fizer Khan
Checkout WTF, formsfrom a creator of Bootstrap Mark otto. It has good styles for checkbox and radio.