如果您希望在单击时在所有浏览器(或至少在 IE、Chrome 和 FF5+ 上)选中一个不确定的复选框,您需要正确初始化选中的属性,如下所示http://jsfiddle.net/K6nrT /6/。我写了以下函数来帮助你:
/// Gives a checkbox the inderminate state and the right
/// checked state so that it becomes checked on click
/// on click on IE, Chrome and Firefox 5+
function makeIndeterminate(checkbox)
{
checkbox.checked = getCheckedStateForIndeterminate();
checkbox.indeterminate = true;
}
以及依赖特征检测的有趣功能:
/// Determine the checked state to give to a checkbox
/// with indeterminate state, so that it becomes checked
/// on click on IE, Chrome and Firefox 5+
function getCheckedStateForIndeterminate()
{
// Create a unchecked checkbox with indeterminate state
var test = document.createElement("input");
test.type = "checkbox";
test.checked = false;
test.indeterminate = true;
// Try to click the checkbox
var body = document.body;
body.appendChild(test); // Required to work on FF
test.click();
body.removeChild(test); // Required to work on FF
// Check if the checkbox is now checked and cache the result
if (test.checked)
{
getCheckedStateForIndeterminate = function () { return false; };
return false;
}
else
{
getCheckedStateForIndeterminate = function () { return true; };
return true;
}
}
没有图像技巧,没有 jQuery,没有额外的属性,也没有涉及事件处理。这仅依赖于简单的 JavaScript 初始化(请注意,不能在 HTML 标记中设置“不确定”属性,因此无论如何都需要 JavaScript 初始化)。