实现中间复选框状态

Materialize intermediate checkbox state

如何让复选框在 Materialise 中未选中时显示为 "indeterminate"?

HTML:

<input type="checkbox" id="test" checked/>
<label for="test" id="test-label">Red</label>

JS:

$('#test-label').click(function() {
    var checkbox = $(this).prev();
    if (!$(checkbox).is(':checked'))
        $(checkbox).prop('indeterminate', true);
});

https://jsfiddle.net/Lhwkfb75/8/

应该是indeterminate而不是intermediate。您可能会因为它们的拼写相似而感到困惑。

$('#test').click(function() {
    if (!$(this).is(':checked'))
        $(this).prop('indeterminate', true);
});

实现此目标有两点很重要:

  1. 阻止默认处理程序
  2. 设置不确定状态时,还必须禁用选中状态,否则虽然复选框显示为中间状态,但$(chk).prop('checked')仍然是true

你好

$('#check-label').click(function(e) {
    e.preventDefault();

    var chk = $("#test");

    if ($(chk).prop( "checked" )) {
        $(chk).prop( "indeterminate" , true );
        $(chk).prop( "checked" , false );
    } else {
        $(chk).prop( "checked" , true );
        $(chk).prop( "indeterminate" , false );
    }

});

甚至更优雅:

$('#check-label').click(function(e) {
    e.preventDefault();

    var chk = $("#test");

    $(chk).prop("checked", !$(chk).prop("checked"));
    $(chk).prop("indeterminate", !$(chk).prop("checked"));

});

参见working fiddle