颜色相同但不透明度不同的对象

5

我有一个对象,其中包含颜色等一系列信息。我希望将这个颜色实现为带有不透明度的背景颜色和文本颜色(没有不透明度以使其看起来不同)。

有人知道如何通过对象/变量的颜色来添加不透明度吗?

演示

.ts

color: string = "green";
name:string = "ABC";
id: number = 1;

.html

<div style="display: flex; flex-direction: column; width: 60%;">
        <span [style.background-color]="color" [style.color]="color" class="cc">{{name}}</span>
        <span [style.background-color]="color" class="mb" [style.color]="color">{{id}}</span>
    </div>
问题

Image

我希望背景色具有透明度,以便文本可见。 我打算实现这一点,而不必创建一个具有“不同”颜色的变量。


你的问题不够清晰,你想要这个不透明度来自哪里?你期望的结果是什么? - user13258211
2个回答

6

您可以在文本和背景之间添加额外的图层,然后在该图层上应用不透明度:

.box {
  padding:10px;
  display:inline-block;
  color:var(--c);
  background:var(--c);
  position:relative;
  z-index:0;
}

.box::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:rgba(255, 255, 255, 0.5);
}
<div class="box" style="--c:red">some text</div>

<div class="box" style="--c:blue">some text</div>

<div class="box" style="--c:green">some text</div>

不使用伪元素的相同思路:

.box {
  padding:10px;
  display:inline-block;
  color:var(--c);
  background:var(--c);
  
  background-image:linear-gradient(rgba(255, 255, 255, 0.5),rgba(255, 255, 255, 0.5))!important;
}
<div class="box" style="--c:red">some text</div>

<div class="box" style="color:blue;background:blue;">some text</div>

<div class="box" style="color:green;background-color:green;">some text</div>


2
您可以使用NPM包color来实现:
import Color from 'color';

const colorWithOpacity = Color(yourColor).alpha(yourOpacity).rgb().string();

您需要调整代码,将colorWithOpacity传递给您的样式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接