我可以在ngStyle中使用 lighten css 属性吗?

3

我尝试在ngStyle中使用lighten属性,但它不起作用。

我的组件中有一个颜色变量,我想像这样使用它:

<div [ngStyle]="{color: schedule.group.color, background: 'lighten(' + schedule.group.color + ', 50%)'}">

有人能给一些想法吗?


schedule.group.color 的值是多少?您不能在行内使用 CSS 函数。您可以直接传递带有 50% 不透明度的 RGBA 值(或在组件中实现 lighten 方法以计算正确的不透明度)。 - marcel
我有一个十六进制颜色值。是的,我知道可以将十六进制转换为RGB并添加不透明度值,但我想知道是否有任何方法可以直接使用十六进制来实现这一点。 - Temo Kiknadze
1
你不能在模板中使用Sass混合。 - David
@TemoKiknadze 像David所说的那样,你不能在内联中使用预处理器函数(sass/less)。唯一的方法是使用rgba。或者一些丑陋的解决方案,比如为文本和背景创建不同的元素。我建议在组件中自己编写一个lighten函数。 - marcel
@TemoKiknadze,我修改了函数和Stackblitz的一些内容。 - Eliseo
显示剩余2条评论
2个回答

2
在CSS中没有“lighten”函数 -它与Less或Sass有关。在互联网上,有JavaScript函数可以实现此功能,例如css.trick中的函数。 更新:重要!(更改函数)
  /**Credits to: https://css-tricks.com/snippets/javascript/lighten-darken-color/ */
  //amt from 0 to 100
  lightenDarkenColor(col, amt) {

    amt=256-Math.floor(amt*5.12)
    const  usePound = col[0]=="#";
    if (usePound)
        col = col.slice(1);

    const num = parseInt(col,16);

    const rr=(num >> 16) + amt;
    const  bb = ((num >> 8) & 0x00FF) + amt;
    const  gg = (num & 0x0000FF) + amt;

    const r=rr>255?255:rr<0?0:rr;
    const b=bb>255?255:bb<0?0:bb;
    const g=gg>255?255:gg<0?0:gg;

    if ((g | (b << 8) | (r << 16))==0)
        return "#000000";

    return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);

  }

使用

<div [ngStyle]="{color: color, 'background-color': lightenDarkenColor(color, 10)}">hello word</div>
<div [ngStyle]="{color: color, 'background-color': lightenDarkenColor(color, 90)}">hello word</div>

请在 stackblitz 中查看演示。

注意:我已将函数更改为从0到100的值,当值超过黑暗时(旧函数返回白色,而应该返回黑色)。 - Eliseo
1
在 https://github.com/Qix-/color 中有一些 JavaScript 函数来操作颜色。 - Eliseo

0

上述(已回答)函数有时会返回空白,然后我找到了解决方案:

hexToRgbNew(hex: any, opacity: any): string {
    let h = hex.replace('#', '');
    h =  h.match(new RegExp('(.{' + h.length / 3 + '})', 'g'));

    for (let i = 0;  i < h.length; i++) {
        h[i] = parseInt(h[i].length === 1 ? h[i] + h[i] : h[i], 16);
    }

    if (typeof opacity !== 'undefined') { h.push(opacity); }

    return 'rgba(' + h.join(',') + ')';
}

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