js 三态按钮,HTML中的三态复选框?

There is no way to have a tri-state check button (yes, no, null) in HTML, right?

Are there any simple tricks or work-arounds without having to render the whole thing by oneself?

解决方案

Edit

Thanks to Janus Troelsen's comment, I found a better solution.

HTML5 defines a property for checkboxes called indeterminate

See w3c reference guide. To make checkbox appear visually indeterminate set it to true:

element.indeterminate = true;

Here is Janus Troelsen's fiddle. Note, however, that:

The indeterminate state cannot be set in the HTML markup, it can only be done via Javascript (see this JSfiddle test and this detailed article in CSS tricks)

This state doesn't change the value of the checkbox, it is only a visual cue that masks the input's real state.

Browser test: Worked for me in Chrome 22, Firefox 15, Opera 12 and back to IE7. Regarding mobile browsers, Android 2.0 browser and Safari mobile on iOS 3.1 don't have support for it.

Previous answer

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);

});

Hope that helps!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值