启用或禁用输入文件时,从CSS更改标签颜色

时间:2018-09-20 07:33:26

标签: html css web-applications css-color

<div class="uploadImgParent">
    <label id="uploadImgButton" for="license" class="uploadImgButton">
         Upload
         <input type="file" id="license" accept="image/*"/>
    </label>
</div>

我有这段代码显示标签(上传),而不显示带有input type="file"标签的标准Button(输入被CSS隐藏,因此我只能显示Upload的标签)。 现在,我希望在启用或禁用按钮时,标签的背景更改颜色

背景色的CSS现在是:

.uploadImgButton{
        color: Black;                   
        background-color: Grey;
        padding: 10px;
        border: double 4px #AAAAAA;
}

现在我可以通过JS控制它,但是我只想通过CSS更改颜色,有什么快速的方法吗? 喜欢:

label:enabled{color: red;}  label:disabled{color:grey;}

1 个答案:

答案 0 :(得分:3)

您可以使用adjacent sibling combinator使用CSS来做到这一点,但是您必须更改布局:

.uploadImgParent {
  display: flex;
  flex-direction: row-reverse;
}
.uploadImgInput {
  margin-right: auto;
}

/* Target labels that goes immediately after ALL inputs */
.uploadImgInput + .uploadImgLabel {
  color: green;
}

/* Target all labels that goes immediately after DISABLED inputs */
.uploadImgInput:disabled + .uploadImgLabel {
  color: red;
}
<div class="uploadImgParent">
    <input class="uploadImgInput" type="file" id="license1" />
    <label class="uploadImgLabel" for="license1">Upload</label>
</div>

<div class="uploadImgParent">
    <input class="uploadImgInput" type="file" id="license2" disabled />
    <label class="uploadImgLabel" for="license2">Upload</label> 
</div>