如何使用不确定的复选框处理浏览器差异

aaa*_*dan 21 html checkbox html-input

Primer:可以将HTML复选框设置为indeterminate,既不选中也不选中.即使在这种不确定的状态下,仍然存在潜在的布尔checked状态.

Mac OS X复选框处于各种状态


单击不确定复选框时,它将失去其indeterminate状态.根据浏览器(Firefox),它还可以切换checked属性.

这个jsfiddle说明了这种情况.在Firefox中,单击其中一个复选框会导致它们切换其初始基础checked状态.在IE中,checked第一次单击时该属性保持不变.

我希望所有浏览器的行为都相同,即使这意味着额外的javascript.不幸的是,该indeterminate属性设置为false 之前onclick处理(或onchange和jQuery change)被调用,所以我无法检测它是否就是所谓的上点击indeterminate复选框或没有.

mouseupkeyup(用于空格键切换)事件显示之前indeterminate的状态,但我宁愿不那么具体:它似乎脆弱.

我可以在复选框(data-indeterminate或类似的)上维护一个单独的属性,但我想知道是否有一个我缺少的简单解决方案,和/或其他人是否有类似的问题.

Gyu*_*Fox 18

如果您希望在所有浏览器上点击(或至少在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;
}
Run Code Online (Sandbox Code Playgroud)

以及依赖于特征检测的有趣功能:

/// 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

没有图像技巧,没有jQuery,没有额外的属性,也没有涉及事件处理.这仅依赖于简单的JavaScript初始化(请注意,不能在HTML标记中设置"indeterminate"属性,因此无论如何都需要JavaScript初始化).

  • 为什么选择downvote?请提供一个不起作用的场景,以便我们可以做得更好 (4认同)
  • 请注意,在复选框离开不确定状态后,IE上不会触发`change`事件.http://jsfiddle.net/paska/K6nrT/20/ (2认同)