YIXUNFE / blog

文章区
151 stars 25 forks source link

checkbox 的第三种状态 #19

Open YIXUNFE opened 8 years ago

YIXUNFE commented 8 years ago

checkbox 的第三种状态

我们知道,checkbox 元素的状态有两种,一种是 checked ,一种是 unchecked 。但实际上,checkbox 元素还有第三种状态 indeterminate


indeterminate 状态

我们看看 MDN 中关于 indeterminate 状态的描述:

The indeterminate attribute is used to indicate that the checkbox is in an indeterminate state (on most platforms, this draws a horizontal line across the checkbox).

indeterminate 属性用于表述 checkbox 元素在一个不确定的状态(在大多数平台中,它被表示成一个横杠)。

firefox chrome
在 Firefox 中的表现 在 Chrome 中的表现


设置 indeterminate 状态

虽然选中状态可以直接在 HTML 中设置,但 indeterminate 状态只能通过 JS 进行设置。

document.querySelector('checkbox').indeterminate = true


CSS 伪类

类似 :checked:unchecked 伪类,我们也可以使用 :indeterminate 伪类进行对不确定状态的 checkbox 的选取。

:indeterminate + span {color: red;}


浏览器兼容性

暂时没有查询到具体的兼容性列表,从网上查看 IE 4.0 已经开始支持该属性。高级浏览器中设置应该也是没问题了。


对表单的影响

indeterminate 状态完全不影响 checkbox 的选中状态。

var chk = document.querySelector('checkbox')

chk.checked = false
chk.indeterminate = true //设置 indeterminate 状态
chk.checked //false

chk.checked = true
chk.indeterminate = true //设置 indeterminate 状态
chk.checked //true

设置 indeterminate 状态不会影响原来的 checkbox 的选中状态。


THANKS


ziquanye commented 8 years ago

原来如此,多谢解惑。