我需要根据另一个 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 助手的做法。那么,您可以使用它来修改 angularjs 应用程序中的颜色属性。
以下示例演示了我为此问题创建的简单 API 的用法,该 API 在彩色模块中作为服务公开。
Disclaimer, it's just a simple module to demonstrate how it can be done, it means I'm not catching all errors and exceptions that could be thrown. Regardless, it's a beautiful module and I'm very proud of it :{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>
关于html - 在 AngularJS 中查找颜色相对于另一种颜色的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40531990/