SASS-根据容器背景色更改颜色

时间:2020-06-22 00:46:15

标签: angular sass colors background-color

我正在尝试创建一个可自定义的标签组件,以使用户可以传入背景颜色,并且希望根据传入的颜色将字体颜色自动设置为亮/暗。

我的组件看起来像这样:

<span class="tag" [ngStyle]="{'backgroundColor': color}">{{ content }}</span>

并且ts文件具有:

@Input() color: string = '#ccc';

我发现了一些使用sass函数的教程,例如:

@function set-notification-text-color($color) {
  @if (lightness($color) > 50) {
    @return #000000; // Lighter backgorund, return dark color
  } @else {
    @return #ffffff; // Darker background, return light color
  }
}

.tag {
  background: $notification-confirm;
  color: set-notification-text-color($notification-confirm);
}

,但它们似乎都在文件本身中定义了 background 属性,而我没有。有没有办法找出应用了'tag'类的当前背景色并改为使用呢?还是另一种通用方式?

1 个答案:

答案 0 :(得分:0)

您需要使用JavaScript来了解颜色是深色还是浅绿色。有不同的形式。如果rgb[0]是红色(0-255),则rgb[1]是绿色(0-255),而rgb[2]是蓝色(0-255)

isLight() {
        const hsp = Math.sqrt(
            0.299 * (this.rgb[0] * this.rgb[0]) +
            0.587 * (this.rgb[1] * this.rgb[1]) +
            0.114 * (this.rgb[2] * this.rgb[2])
        );
        return hsp < 127.5;
}

isLight() {
    const luminance =
        (0.2126 * this.rgb[0] / 255) +
        (0.7152 * this.rgb[1] / 255) +
        (0.0722 * this.rgb[2] / 255);
    return luminance>.5
}

有一些用于管理颜色的库。如果您愿意,可以选中此stackblitz或寻找另一个