【问题标题】:SASS - Change color based on container background colorSASS - 根据容器背景颜色更改颜色
【发布时间】:2020-10-11 19:34:00
【问题描述】:

我正在尝试以角度创建可自定义的标签组件,用户将在其中传递背景颜色,并且我希望根据传入的颜色将字体颜色自动设置为浅色/深色。

我的组件如下所示:

<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 属性,而我没有。有没有办法找出应用“标签”类的当前背景颜色并改用它?还是其他通用方式?

【问题讨论】:

  • 如果将 {{content}} 包裹在另一个 中并将内部跨度的颜色属性设置为 'inherit' 会怎样?

标签: angular sass colors background-color


【解决方案1】:

您需要使用 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 或寻找另一个

【讨论】:

    猜你喜欢
    • 2014-03-15
    • 2022-10-18
    • 1970-01-01
    • 2016-06-02
    • 2019-06-20
    • 2014-08-17
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    相关资源
    最近更新 更多