共计 1122 个字符,预计需要花费 3 分钟才能阅读完成。
CSS :checked
伪类用于匹配被用户选中的单选按钮 Radio 或复选按钮 checkbox。
:checked
伪类用于匹配页面中的 <input type="checkbox">
,或<input type="radio">
,或在<select></select>
元素中的 <option></option>
选项,当这些元素处于选中状态时,就会被添加 :checked
伪类。
你可以在 <input type="radio">
和<input type="checkbox">
中使用 checked
属性,或在下拉列表的 option
选项中使用 selected
选项来表明该项目被选中。
<input type="radio" checked>
<input type="checkbox" checked>
<select name="options" id="list">
<option value="Something" selected>This option is selected</option>
<option value="Something-else">This one is not</option>
</select>
单选按钮和复选按钮默认为 :checked
状态,你可以通过单击来取消选中状态。
:checked
伪类和 label
标签配合使用,可以制作出一些有趣的视觉效果。例如下面的例子,在复选框处于选中状态时,复选框的文本会被设置为红色。
<input type="checkbox" id="todo">
<label for="todo"> 是否选中?</label>
input[type = "checkbox"]:checked + label {color: red;}
得到的结果如下:
是否选中?
示例代码
/* 表示页面上的所有选中的 radio 按钮 */
input[type="radio"]:checked{
width: 20px;
height: 20px;
}
/* 表示页面上的所有选中的 checkbox 按钮 */
input[type="checkbox"]:checked{color: red;}
/* 表示页面上的所有选中的 select 的选项 */
option:checked{color: green;}
在线演示
下面的例子使用 :checked
伪类来自定义复选框的样式。
Red
Yellow
Green
Brown
浏览器支持
所有的现代浏览器都支持 :checked
伪类,包括:Chrome, Firefox, Safari, Opera9+, Internet Explorer 9+ 以及 Android 和 iOS。