如何在运行时css上根据背景颜色更改文本的颜色

问题描述 投票:0回答:1

我有

<span [ngStyle]="{'background-color': dynamicColor}">ABC</span>

我想根据background-color反色的背景颜色设置文本的字体颜色,以便于阅读。就像background-color是白色的那样,文字颜色应该是黑色的。如果background-color是黑色,那么文字颜色是白色。

在sass中,我可以使用以下功能轻松完成此操作

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

但是background-color正在根据使用AJAX的动态内容改变运行时间。

更新

添加了更多细节以清除问题。

css
1个回答
0
投票

当ngStyle改变时,改变颜色!

元件:

<span ngStyle="{\"backgroundColor\":\"#000\"}">ABC</span>

JS:

setTimeout(function() { 
    var dom = document.querySelector("[ngStyle]");
    var temp = JSON.parse(dom.getAttribute("ngStyle"));
    dom.style.color = (temp.backgroundColor === "#000" ? "#fff" : "#000")
}, 16)
© www.soinside.com 2019 - 2024. All rights reserved.