【问题标题】:Change label color when textarea has value当 textarea 有值时更改标签颜色
【发布时间】:2019-01-08 12:39:16
【问题描述】:

当 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 时,它可以很好地使用以下代码:

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

但是,我需要这个颜色: color: #ff8086;当我们没有任何值时,当在 textarea 上写任何东西时是绿色的(如上图所示)。

我试过 :active ,但它只在鼠标点击时有效:

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

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

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

【问题讨论】:

  • 我不认为你可以用 css/sass 做某事

标签: css sass textarea


【解决方案1】:

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

textarea:valid + label{
  background: #ff0000;
}
&lt;textarea required="required"&gt;&lt;/textarea&gt;&lt;label&gt;label&lt;/label&gt;

【讨论】:

    【解决方案2】:

    你也可以这样试试,和上面一样可以正常工作:

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

    【讨论】:

      【解决方案3】:

      另一个选项,避免使用&lt;textarea&gt; 和其他表单元素,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.

      参考资料:

      【讨论】:

        猜你喜欢
        • 2013-12-17
        • 1970-01-01
        • 1970-01-01
        • 2015-03-31
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        • 2018-07-08
        • 1970-01-01
        相关资源
        最近更新 更多