130

我知道有一个官方的 CSS3:checked伪类,但是有一个:unchecked伪类吗,它们有相同的浏览器支持吗?

Sitepoint 的参考资料没有提到,但是这个whatwg 规范(不管是什么)确实如此。

:checked我知道将和伪类结合起来可以达到相同的结果:not(),但我仍然很好奇:

input[type="checkbox"]:not(:checked) {
    /* styles */
}

编辑:

w3c 推荐相同的技术

可以使用否定伪类来选择未选中的复选框:

:not(:checked)
4

4 回答 4

124

:unchecked is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.

In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked), it's safe to assume that there is no corresponding :unchecked pseudo. Browser support for :not() and :checked is identical, so that shouldn't be a problem.

This may seem inconsistent with the :enabled and :disabled states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.

(:indeterminate does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)

于 2012-03-19T16:28:51.370 回答
43

我认为您试图使事情复杂化。一个简单的解决方案是默认使用未选中样式设置复选框的样式,然后添加选中状态样式。

input[type="checkbox"] {
  // Unchecked Styles
}
input[type="checkbox"]:checked {
  // Checked Styles
}

我为提出一个旧线程而道歉,但觉得它可以使用更好的答案。

编辑(2016 年 3 月 3 日):

W3C 规范将:not(:checked)其作为选择未选中状态的示例。但是,这明确是未选中状态,并且只会将这些样式应用于未选中状态。这对于添加仅在未选中状态下需要并且如果在选择器上使用则需要从选中状态中删除的样式很有用input[type="checkbox"]。请参阅下面的示例以进行说明。

input[type="checkbox"] {
  /* Base Styles aka unchecked */
  font-weight: 300; // Will be overwritten by :checked
  font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
  /* Explicit Unchecked Styles */
  border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
  /* Checked Styles */
  font-weight: 900; // Use a bold font when checked
}

如果不使用:not(:checked)上面的示例,:checked选择器将需要使用 aborder: none;来实现相同的效果。

使用input[type="checkbox"]for 基本样式来减少重复。

input[type="checkbox"]:not(:checked)用于您不想应用于选中状态的显式未选中样式。

于 2015-05-21T16:34:38.570 回答
4

没有 :unchecked 伪类,但是如果你使用 :checked 伪类和兄弟选择器,你可以区分这两种状态。我相信所有最新的浏览器都支持 :checked 伪类,你可以从这个资源中找到更多信息:http: //www.whatstyle.net/articles/18/pretty_form_controls_with_css

您将通过 jquery 获得更好的浏览器支持...您可以使用点击功能来检测点击何时发生以及是否选中,然后您可以根据需要添加一个类或删除一个类...

于 2012-01-13T04:54:35.770 回答
-2

我处理这个问题的方法是根据条件切换标签的类名。这样,您只需要一个标签,并且可以为不同的州提供不同的类别……希望对您有所帮助!

于 2017-06-12T22:10:07.083 回答