簡體   English   中英

有沒有辦法根據 CSS 中另一個元素的背景顏色來更改文本的顏色?

[英]is there a way to change the color of the text depending on the background color of another element in CSS?

在我的項目中,span 元素用於顯示錯誤消息或控制標簽。 消息的文本顏色為紅色,我需要根據元素(fe f1 元素)的背景顏色設置文本顏色,該元素位於 UI 中的 span 元素后面,因為我在不同的輸入元素上使用錯誤消息不同的背景 colors。 有沒有辦法解決這個問題? 提前致謝。

主題.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;
}

您可以使用ngClass指令根據特定的 state 從元素中添加或刪除類。 在這里閱讀更多https://angular.io/api/common/NgClass

例子

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

然后在你的樣式文件中

span.isError{
    color: white;
}

如果我了解您想要更改文本顏色取決於動態的背景顏色:

您可以創建一個 angular 組件:

<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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM