在AngularJS中查找颜色相对于其他颜色的百分比



我需要根据另一个div元素的颜色来改变一个div元素的颜色。

交货。

 <div style="background-color:{{color_primary}};">

在另一个DIV中,颜色应为color_primary

的70%(浅色)
<div style="background-color:{{this color is 70% of color_primary}};">

我怎样才能实现它?

您可以通过将此百分比应用于每个RGB组件来实现这一点,类似于SASS和LESS helper的做法。因此,你可以使用它来修改angularjs应用程序中的颜色属性。

下面的示例演示了我为这个问题创建的一个简单API的用法,该API在着色模块中作为服务公开。

免责声明,这只是一个简单的模块来演示它是如何做到的,这意味着我没有捕捉到所有可能抛出的错误和异常。无论如何,它是一个漂亮的模块,我为它感到非常自豪:{D

使用

angular.module('myApp', ['colorized'])    
    .controller('myController', function ($colors) {
        var $ctrl = this;
        $ctrl.myLightenColor = $colors.lighten('#000000', 50); // 50% gray        
    });

colorized模块加上一个简单的例子:

// The module
(function() {
  angular.module('colorized', [])
    .service('$colors', function() {
      this.lighten = function(src, percent) {
        var src = normalizeColor(src);
        if (!percent) return src;
        var srcRGB = colorAsArray(src),
          // you may want to change it to keep a different
          // range, for example, the range between the actual
          // collor and the full white collor, it's up to you
          lightFactor = (255 * percent) / 100,
          newRGB = {
            r: limited(srcRGB.r + lightFactor, 255),
            g: limited(srcRGB.g + lightFactor, 255),
            b: limited(srcRGB.b + lightFactor, 255),
          };
        return [
          padRGBDigit(newRGB.r.toString(16)),
          padRGBDigit(newRGB.g.toString(16)),
          padRGBDigit(newRGB.b.toString(16))
        ].join('');
      }
      function normalizeColor(color) {
        if (color == undefined) color = '000000';
        if (color[0] == '#') color = color.substring(1);
        return color;
      }
      function colorAsArray(color) {
        return {
          r: parseInt(color.substring(0, 2), 16),
          g: parseInt(color.substring(2, 4), 16),
          b: parseInt(color.substring(4, 8), 16),
        };
      }
      function limited(value, limit) {
        return Math.ceil(value > limit ? limit : value);
      }
      function padRGBDigit(str) {
        return ('00' + str).slice(-2);
      }
    });
})();
// my app
(function() {
  angular.module('myApp', ['colorized'])
    .controller('myController', function($scope, $colors) {
      $scope.mySourceColor = '#000000';
      $scope.myPercentage = 50;
      $scope.myLightColor = function() {
        return '#' + $colors.lighten($scope.mySourceColor, $scope.myPercentage);
      };
    });
  angular.element(document).ready(function() {
    angular.bootstrap(document, ['myApp']);
  });
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<div ng-controller="myController">
  <input type="color" ng-model="mySourceColor">
  <input ng-style="{'background-color': myLightColor()}" type="range" ng-model="myPercentage" min="0" max="100">
  <span>
  {{ myLightColor() }}
</span>
</div>

相关内容