【问题标题】:How to automatically change text color base on background color in Angularjs? [duplicate]如何根据Angularjs中的背景颜色自动更改文本颜色? [复制]
【发布时间】:2019-12-10 15:55:17
【问题描述】:

我正在使用ng-style 在团队列表中标记类似团队标签的东西,我想让团队的名称将根据填充团队名称覆盖区域背景的颜色来更改.问题是如果背景颜色的亮度会变暗,文本颜色会导致团队名称变暗,用户无法阅读。那我该怎么做呢?

  • HTML:
<tr ng-repeat="team in teams">
   <td>{{ team.id }}</td>
   <td><span ng-style="setColor(team.color)" style="color: #888;">{{ team.name }}</span></td>
</tr>
  • 控制器:
app.controller('teamController', function($scope){
  $scope.teams = [
     {
       id: '1',
       name: 'Driver',
       color: '#b9774d'
     },
     {
       id: '2',
       name: 'Finance',
       color: '#FEFFB3'
     }
  ];

  $scope.setColor = function (color){
     return {background: color};
  }
});

【问题讨论】:

  • css-tricks上有一篇文章非常透彻地讨论了这个案例,你应该看看。
  • 感谢您的回答,我会阅读这篇文章以更深入地挖掘 css。 =D

标签: javascript css angularjs ng-style


【解决方案1】:

要在table 中使用ng-repeat,您必须在tabletbody 标签中应用ng-repeat。

更新的 plunker 链接是Working Plunker

ng-repeat 指令顾名思义根据集合的长度重复元素,在这种情况下它将重复 TR 元素(HTML 表格行)。 HTML 表的 TBODY 元素已分配 ng-repeat 指令,以便遍历 Customers JSON 数组的所有项目。 对于 Customers JSON 数组中的每个 JSON 对象,都会生成一个 TR 元素(HTML 表格行)并将其附加到 HTML 表格中。

【讨论】:

  • 我稍后会更改它,但我的主要问题是动态文本颜色与背景颜色。
【解决方案2】:

这是一个基于输入颜色创建另一种颜色的函数:

 $scope.setColor = function (color) {
    colorInt = parseInt(color.slice(1),16);
    //Create other color
    otherColor = colorInt ^ 0x1FFFFFF;
    console.log(colorInt.toString(16),otherColor.toString(16));
    return {
      background: color,
      color: '#'+otherColor.toString(16).slice(1)
    };
 }

DEMO on PLNKR

【讨论】:

    【解决方案3】:

    最后,我找到了自己的解决方案。我有一个函数可以将hex 字符串转换为rgb 然后我使用一些逻辑来处理字体颜色。这是一些代码。

    $scope.setColor = function (color) {
        var rbg = hex2rgb(color);
        var o = Math.round(((parseInt(rbg[0]) * 299) +
                (parseInt(rbg[1]) * 587) +
                (parseInt(rbg[2]) * 114)) / 1000);
        var force = (o > 200) ? '#888' : 'white';
        return {background: color, color: force};
    };
    function hex2rgb( colour ) {
        var r,g,b;
        if ( colour.charAt(0) === '#' ) {
            colour = colour.substr(1);
        }
        if ( colour.length === 3 ) {
            colour = colour.substr(0,1) + colour.substr(0,1) + colour.substr(1,2) + colour.substr(1,2) + colour.substr(2,3) + colour.substr(2,3);
        }
        r = colour.charAt(0) + '' + colour.charAt(1);
        g = colour.charAt(2) + '' + colour.charAt(3);
        b = colour.charAt(4) + '' + colour.charAt(5);
        r = parseInt( r,16 );
        g = parseInt( g,16 );
        b = parseInt( b ,16);
        return [r, g, b];
    }
    

    参考来源:

    1. https://stackoverflow.com/a/12944084/11580916

    2. https://stackoverflow.com/a/11868159/11580916

    【讨论】:

      猜你喜欢
      • 2016-06-02
      • 1970-01-01
      • 2022-10-18
      • 2015-12-31
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多