入门:可以将 HTML 复选框设置为 indeterminate
,这会将其显示为既未选中也未未选中。即使在这种不确定的状态下,仍然有一个底层 bool 值 checked
状态。
当一个不确定的复选框被点击时,它会失去它的 indeterminate
状态。根据浏览器 (Firefox),它还可以切换 checked
属性。
This jsfiddle说明情况。在 Firefox 中,单击任何一个复选框都会导致它们切换其初始基础 checked
状态。在 IE 中,checked
属性在第一次点击时保持不变。
我希望所有浏览器的行为都相同,即使这意味着额外的 javascript。不幸的是,indeterminate
属性在 onclick
处理程序(或 onchange
和 jquery change
) 被调用,所以我无法检测是否调用了 indeterminate
复选框。
mouseup
和 keyup
(用于空格键切换)事件显示之前的 indeterminate
状态,但我不想说得那么具体:它看起来很脆弱。
我可以在复选框上维护一个单独的属性(data-indeterminate
或类似的),但我想知道是否有一个我缺少的简单解决方案,和/或其他人是否有类似的问题。
最佳答案
如果你想要一个不确定的复选框,它在点击时在所有浏览器上都被选中(或者至少在 IE、Chrome 和 FF5+ 上),你需要正确地初始化 checked 属性,如图所示这里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 初始化)。
关于html - 如何处理不确定复选框的浏览器差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433472/