Javascript 如何使html复选框变灰?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10685048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:30:25  来源:igfitidea点击:

How to gray out an html checkbox?

javascriptjquerycss

提问by Roman

I want to make readonly checkbox. Like this:

我想设置只读复选框。像这样:

<input type="checkbox" onclick="return false;">

I want the checkbox to look like it is disabled or grayed out.

我希望复选框看起来像是被禁用或变灰。

How can I do this?

我怎样才能做到这一点?

采纳答案by FluffyKitten

You need to disable the checkbox also:

您还需要禁用该复选框:

<input type="checkbox" onclick="return false;" disabled="disabled">

To post the value, simply make it readonly instead:

要发布该值,只需将其设为只读即可:

<input type="checkbox" onclick="return false;" readonly="readonly">

You can style checkbox label and readonly inputs with CSS, e.g.: input [readonly="readonly"] {} but the browser should make the checkbox should appear greyed out when set to readonly.

您可以使用 CSS 设置复选框标签和只读输入的样式,例如: input [readonly="readonly"] {} 但是当设置为只读时,浏览器应该使复选框显示为灰色。

Updated:

更新:

You are at the the mercy of the browser when styling checkboxes & to style them consistently across all browsers, you have to resort to images e.g.: http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/

在设置复选框样式并在所有浏览器中始终如一地设置它们的样式时,您受浏览器的支配,您必须求助于图像,例如:http: //ryanfait.com/resources/custom-checkboxes-and-radio-buttons/

If you don't want to do this (and it seems like a longwinded solution), the simplest solution is to disable the checkbox so it appears correctly, and post the value as a hidden input e.g.:

如果您不想这样做(这似乎是一个冗长的解决方案),最简单的解决方案是禁用复选框使其正确显示,并将该值作为隐藏输入发布,例如:

<input type="checkbox" onclick="return false;" disabled="disabled">
<input type="hidden" name="checkboxval" value="111" />

回答by Fabrizio Calderan

<input type="checkbox" class="readonly">

Css

css

input.readonly {
   opacity : .50;
   filter  : alpha(opacity=50); /* IE<9 */
   cursor  : default;
}

js

js

$('input.readonly').on('click', function(evt) {
   evt.preventDefault();
}

Add a class readonlyto the element you want to grayout: via css you set an opacityand change the style of cursor. Then remove inline javascript and prevent the default action for input.readonlyelements on click event

readonly向要灰显的元素添加一个类:通过 css 设置 anopacity并更改cursor. 然后删除内联 javascript 并阻止input.readonly点击事件元素的默认操作

回答by Christian Long

Simple, css-only way to gray-out a disabled checkbox.

将禁用的复选框灰显的简单、仅 css 的方法。

input[type=checkbox][disabled] {
    filter: invert(25%);
}

回答by Talha

simply add the 'disabled' attribute on checkbox like this

只需像这样在复选框上添加“禁用”属性

<input type="checkbox" disabled="disabled" />