【问题标题】:is there a way to change the color of the text depending on the background color of another element in CSS?有没有办法根据 CSS 中另一个元素的背景颜色来改变文本的颜色?
【发布时间】:2021-04-09 02:10:14
【问题描述】:

在我的项目中,span 元素用于显示错误消息或控件标签。消息的文本颜色是红色,我需要根据元素的背景颜色(例如 f1 元素)设置文本颜色,因为我在不同的输入元素上使用错误消息不同的背景颜色。有没有办法解决这个问题?提前致谢。

theme.scss 文件

.has-error .help-block, .has-error .control-label {
  color: red;
}

login.component.html 文件

<form #form="ngForm" (ngSubmit)="onSubmit(form, $event)">
  <div upeFormGroup hasFeedback [hasError]="un.invalid">
    <div class="input-group">
      <input type="text"
             [(ngModel)]="user.username"
             upeFormControl
             name="username"
             #un="ngModel"
             placeholder="User"
             required>
    </div>
    <span [upeHelpBlock]="un.invalid">Please fill the name input</span>
  </div>
</form>

auth.component.html 文件

<div fxFlex="grow">
   <div class="form-box">
     <router-outlet></router-outlet>
   </div>
</div>

auth.component.scss 文件

.form-box {
   background-color: gray;
}

【问题讨论】:

    标签: javascript html css angular sass


    【解决方案1】:

    您可以使用ngClass 指令根据特定状态从元素中添加或删除类。在此处阅读更多信息https://angular.io/api/common/NgClass

    示例

    <span [ngClass]="{isError:un.invalid}">Please fill the name input</span>
    

    然后在你的样式文件中

    span.isError{
        color: white;
    }
    

    【讨论】:

    • 也许我必须改正我的问题。具有 .has-error .help-block 类名的 span 元素在项目中的不同组件中使用,对于每个组件,我想根据不同元素的 bg 颜色设置不同的文本颜色(在上面的示例中,取决于 .form-b​​ox bg 颜色)。
    • 看看这个stackoverflow.com/questions/36527605/…也许会有所帮助。
    【解决方案2】:

    如果我了解您想要更改文本颜色取决于动态的背景颜色:

    你可以创建一个角度组件:

    <form #form="ngForm" (ngSubmit)="onSubmit(form, $event)">
      <div upeFormGroup hasFeedback [hasError]="un.invalid">
        <div class="input-group">
          <input type="text"
                 [(ngModel)]="user.username"
                 upeFormControl
                 name="username"
                 #un="ngModel"
                 placeholder="User"
                 required>
        </div>
        <app-error [ ... ] [isInvert]="isInvert" [message]="message"></app-error>
      </div>
    </form>
    

    应用程序错误:

    
    <span [ngStyle]="{color: '#000', filter: (isInvert ? 'invert(1)' : 'invert(0)')}">
       {{message}}
    </span>
    
    // for black and white but use css class for more colors
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-10
      • 2023-03-14
      • 2016-06-02
      • 2019-01-08
      • 1970-01-01
      • 2019-06-20
      • 2023-02-10
      • 1970-01-01
      相关资源
      最近更新 更多