html - HTML中的三态复选框?

标签 html forms checkbox

没有办法在 HTML 中设置三态检查按钮(是、否、null),对吧?

有没有什么简单的技巧或变通方法,而不必自己渲染整个东西?

最佳答案

编辑 — 感谢 Janus Troelsen 的评论,我找到了更好的解决方案:

HTML5 为复选框定义了一个名为 indeterminate

的属性

w3c reference guide .要使复选框在视觉上不确定,请将其设置为 true:

element.indeterminate = true;

这里是 Janus Troelsen's fiddle .但请注意:

  • indeterminate 状态不能在 HTML 标记中设置,只能通过 Javascript 来完成(参见 JSfiddle testdetailed article in CSS tricks)

  • 这种状态不会改变复选框的值,它只是一个视觉提示,掩盖了输入的真实状态。

  • 浏览器测试:在 Chrome 22、Firefox 15、Opera 12 和 IE7 中为我工作。关于移动浏览器,Android 2.0 浏览器和 iOS 3.1 上的 Safari mobile 不支持。

上一个答案

Another alternative would be to play with the checkbox transparency for the "some selected" state (as Gmail does used to do in previous versions). It will require some javascript and a CSS class. Here I put a particular example that handles a list with checkable items and a checkbox that allows to select all/none of them. This checkbox shows a "some selected" state when some of the list items are selected.

Given a checkbox with an ID #select_all and several checkboxes with a class .select_one,

The CSS class that fades the "select all" checkbox would be the following:

.some_selected {
    opacity: 0.5;
    filter: alpha(opacity=50);
}

And the JS code that handles the tri-state of the select all checkbox is the following:

$('#select_all').change (function ()
{
    //Check/uncheck all the list's checkboxes
    $('.select_one').attr('checked', $(this).is(':checked'));
    //Remove the faded state
    $(this).removeClass('some_selected');
});

$('.select_one').change (function ()
{
  if ($('.select_one:checked').length == 0)
      $('#select_all').removeClass('some_selected').attr('checked', false);
  else if ($('.select_one:not(:checked)').length == 0)
      $('#select_all').removeClass('some_selected').attr('checked', true);
  else
      $('#select_all').addClass('some_selected').attr('checked', true);
});

You can try it here: http://jsfiddle.net/98BMK/

Hope that helps!

关于html - HTML中的三态复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1726096/

相关文章:

javascript - Rails Ajax 表单没有响应

javascript - 单击调查表中的提交后的用户详细信息表单

javascript - 反转复选框值,以便在模型中检查为 false

javascript - 我做错了什么?

javascript - 文档开头不允许使用 XML

javascript - 从 .csv 文件读取的内容有时不会在页面加载时显示

javascript - 使用javascript改变显示

html - 颜色未显示在打印预览中,但显示在简单 View 中

checkbox - 请求对话框复选框选项 "don' 发送前询问...”

Javascript 按钮在表单标签中不起作用