我正在尝试为自己创建一个简单的实用程序,以便能够将值从 RGB 转换为十六进制,反之亦然。除了一个缺陷之外,它在大多数情况下都有效。
如果我输入像 '007aff'
这样的十六进制值,'00'
会被 trim ,结果为 '7aff'
。 r/g/b/仍然获得正确的值,但我不希望从十六进制值中删除零。我做错了什么吗?
// for anyone unfamiliar with angular
// $watch runs when the variable in quotes changes in value
// the rest is basic javascript
AngularJS:
$scope.$watch('hex', function() {
var rgb = parseInt($scope.hex, 16);
$scope.r = (rgb >> 16) & 0xFF;
$scope.g = (rgb >> 8) & 0xFF;
$scope.b = rgb & 0xFF;
$scope.rgb = 'rgb(' + $scope.r + ',' + $scope.g + ',' + $scope.b + ');';
});
$scope.$watch('r+g+b', function() {
$scope.rgb = 'rgb(' + $scope.r + ',' + $scope.g + ',' + $scope.b + ');';
$scope.hex = parseInt($scope.r << 16 | $scope.g << 8 | $scope.b).toString(16);
});
最佳答案
00
并未直接 trim 。当您将 rgb 数字 转换为字符串时,您不会使用前导零对其进行格式化。
尝试使用前导零进行格式化:
var value = parseInt($scope.r << 16 | $scope.g << 8 | $scope.b);
$scope.hex = ('000000' + value.toString(16)).slice(-6);
关于javascript ->> 按位运算符未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25392438/