当textarea有价值时更改标签颜色

时间:2019-01-08 12:39:16

标签: css css3 sass textarea

当textarea接收到一些值时,我需要更改标签的颜色。

<form action="#" class="form-reverse">
   <textarea name="order-background__bussiness" id="order-background__bussiness" cols="30" rows="10"></textarea>
   <label for="order-background__bussiness">What are the company’s objectives?</label>
</form>

当我们重点关注文本区域时,此代码可以正常工作:

textarea:focus ~ label{
        color: #55c57a;
}

enter image description here

但是,我需要这种颜色:color:#ff8086;当我们没有任何值时,当文本区域上写有任何值时,绿色(如上图所示)。

我尝试了:active,但是仅在单击鼠标时有效:

textarea:active ~ label{
        color: #ff8086;
}

enter image description here

也许有人对此有解决方案?

PS:我确实有JS解决方案,但我很好奇SASS是否也有解决方案?

3 个答案:

答案 0 :(得分:2)

您可以使用css有效属性,如果textarea是有效字段,则它将匹配,您可以设置必需的属性,如果有效,它将与有效选择器匹配... https://www.w3schools.com/cssref/sel_valid.asp

textarea:valid + label{
  background: #ff0000;
}
<textarea required="required"></textarea><label>label</label>

答案 1 :(得分:0)

您也可以这样尝试,这样可以正常工作:

 textarea:not(:invalid) + label{
  background: #ff0000;
}

答案 2 :(得分:0)

另一种避免使用<textarea>和其他表单元素的选项required使用:placeholder-shown伪类;当然,这确实需要设置placeholder属性(尽管可以将其设置为空格或零长度的字符串):

/* selects a <label> element immediately adjacent to
   an element which has its placeholder string visible
   to the user: */
:placeholder-shown+label {
  color: #f90;
}

/* this selects all <label> elements, but is less specific
   than the selector above; so will be 'overridden' in the
   event that the previous selector matches: */
label {
  color: limegreen;
  font-size: 1.5em;
}

*,
 ::before,
 ::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-size: 1rem;
}

.form-reverse {
  display: flex;
  flex-direction: column-reverse;
  width: 80vw;
  margin: 0 auto;
}

textarea {
  width: 100%;
  min-height: 30vh;
}

:placeholder-shown+label {
  color: #f90;
}

label {
  color: limegreen;
  font-size: 1.5em;
}
<form action="#" class="form-reverse">
  <textarea name="order-background__bussiness" id="order-background__bussiness" placeholder=" "></textarea>
  <label for="order-background__bussiness">What are the company’s objectives?</label>
</form>

JS Fiddle demo

参考文献: