jQuery 禁用输入时如何更改 <label> 的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7330541/
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-26 23:42:41  来源:igfitidea点击:

How can I change a <label>’s color when its input is disabled?

jquerycss

提问by Ivan

I have some labels like:

我有一些标签,例如:

  <label>
     <input type="checkbox" name="the_name" id="the_name" /> Label text
  </label>

that sometimes are disabled

有时被禁用

$("#the_name").prop('disabled', true);

No problem, but I would like to change label text color to make it more visible. Is it possible using Jquery and/or CSS?

没问题,但我想更改标签文本颜色以使其更明显。是否可以使用 Jquery 和/或 CSS?

采纳答案by Billy Moon

you can add a css rule to the label by selecting the parent of your input and adding to that at the time you disable the control

您可以通过选择输入的父级并在禁用控件时添加到标签中来向标签添加 css 规则

$("#the_name").prop('disabled', true).parent().css({backgroundColor:'#fcc'});


Additionally, I think label is meant to be used like this:

此外,我认为 label 应该这样使用:

<label for="the_id">Label text</label>
<input type="checkbox" name="the_name" id="the_id" />

where the label's forattribute matches the idof the target control

其中标签的for属性与id目标控件的匹配

in which case you could select the label by it's forattribute and apply css as you see fit - something like this:

在这种情况下,您可以通过它的for属性选择标签并根据需要应用 css - 如下所示:

$("#the_id").prop('disabled', true);
$('label[for=the_id]').css({backgroundColor:'#fcc'});

See fiddle for demo: http://jsfiddle.net/bq52X/

见小提琴演示:http: //jsfiddle.net/bq52X/

回答by Dag Sondre Hansen

This can be done in CSS, but only when the label comes after the input tag. For example:

这可以在 CSS 中完成,但仅当标签出现在输入标签之后时。例如:

HTML:

HTML:

<input id="someinput" type="text" /><label for="someinput">Type text:</label> 

CSS:

CSS:

input[disabled] + label { *whatever style you want when input is disabled* } ;

回答by Tim B James

Yeah if you are wanting to make the disabled inputs label text a different color, then you could add a css class to the <label>tag.

是的,如果您想让禁用的输入标签文本具有不同的颜色,那么您可以向<label>标签添加一个 css 类。

$("#the_name").prop('disabled', true).parent('label').addClass('disabled-label');

Then you have control over the style through the stylesheet rather than in the script file or the html file.

然后您可以通过样式表而不是在脚本文件或 html 文件中控制样式。

Consider not wrapping the input inside the label tag though as i feel it gives you greater control over styles.

考虑不要将输入包装在标签标签内,因为我觉得它可以让您更好地控制样式。

回答by ziiweb

I didn't hear anyone about opacity:

我没有听到任何关于不透明度的消息:

.css('opacity', '0.5');

回答by ziiweb

One option:

一种选择:

$("#the_name").parent('label').css('color','silver');