这篇经验要分享的是复选框的不确定状态的,html中的复选框是:
<input id="cb" type="checkbox"/>
一般遇到复选框或许只需要选中或者不选中两种状态即可,但是有时候需要第三种不确定状态,例如做带复选框的级联菜单时,子级菜单的多个复选框为部分选中的时,父级菜单的复选框应处于不确定状态,来反映子菜单的部分选中情况。
方法是通过js设置复选框的indeterminate属性,在标签中设置此属性无效。
<html>
<head>
<script>
function init(){
chkbox = document.getElementById("cb");
}
function fun1 () {
chkbox.indeterminate = false;
chkbox.checked = true;
}
function fun2() {
chkbox.indeterminate = false;
chkbox.checked = false;
}
function fun3() {
chkbox.indeterminate = true;
}
</script>
</head>
<body onload="init()">
<input id="cb" type="checkbox" />
<button onclick="fun1()">选中</button>
<button onclick="fun2()">不选</button>
<button onclick="fun3()">部分选中</button>
</Body>
</html>
另外,复选框的属性checked,在这个标签中只要设置了checked,复选框初始化时都是选中状态,包括不限于一下四种:
checked="true"
checked="false"
checked=""
checked
所以,如果要初始显示为不选中的状态,不设置checked属性即可。