在 Javascript 中更轻松地使用十六进制字符串和十六进制值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11023144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Working with hex strings and hex values more easily in Javascript
提问by brentonstrine
I am taking strings which represent hexadecimal numbers (actually, hex colors) and adding them. So, adding aaaaaa
+ 010101
= ababab
. My method seems unnecessarily long and complicated:
我正在取代表十六进制数字(实际上是十六进制颜色)的字符串并将它们相加。因此,添加aaaaaa
+ 010101
= ababab
。我的方法似乎不必要地冗长和复杂:
var hexValue = "aaaaaa";
hexValue = "0x" + hexValue;
hexValue = parseInt(hexValue , 16);
hexValue = hexValue + 0x010101;
hexValue = hexValue.toString(16);
document.write(hexValue); // outputs 'ababab'
- (JsFiddle: http://jsfiddle.net/U92vt/1/)
- (JsFiddle:http: //jsfiddle.net/U92vt/1/)
The hex value is still a string after concatenating 0x
, so then I have to change it to a number, thenI can add, thenI have to change it backinto hex format! There are even more steps if the number I'm adding to it is a hexadecimal string to begin with as well, or if you take into consideration that I am removing the #
from the hex color before all this starts.
连接后十六进制值还是字符串0x
,所以那我得把它改成数字,然后才能加,然后我得把它改回十六进制格式!如果我添加的数字也是以十六进制字符串开头,或者您考虑到我正在#
所有这些开始之前从十六进制颜色中删除,则还有更多步骤。
Surely there's a way to do this with less steps! (And I don't mean just putting it all on one line (parseInt("0x"+"aaaaaa",16)+0x010101).toString(16)
or using shorthand, I mean actually doing less operations.)
当然有一种方法可以用更少的步骤做到这一点!(我的意思不是将所有内容放在一行(parseInt("0x"+"aaaaaa",16)+0x010101).toString(16)
或使用速记,我的意思是实际上做的操作更少。)
Is there some way to get Javascript to stop using decimal for all of its mathematical operations and use hex instead? Or is there some other method of making Javascript work with Hex more easily?
有没有办法让Javascript停止使用十进制进行所有数学运算并使用十六进制代替?或者是否有其他一些方法可以让 Javascript 更轻松地与 Hex 一起工作?
回答by maerics
No, there is no way to tell the JavaScript language to use hex integer format instead of decimal by default. Your code is about as concise as it gets but note that you do not need to prepend the "0x" base indicator when you use "parseInt" with a base.
不,没有办法告诉 JavaScript 语言默认使用十六进制整数格式而不是十进制。您的代码尽可能简洁,但请注意,当您将“parseInt”与基数一起使用时,您不需要预先添加“0x”基数指示符。
Here is how I would approach your problem:
以下是我将如何解决您的问题:
function addHexColor(c1, c2) {
var hexStr = (parseInt(c1, 16) + parseInt(c2, 16)).toString(16);
while (hexStr.length < 6) { hexStr = '0' + hexStr; } // Zero pad.
return hexStr;
}
addHexColor('aaaaaa', '010101'); // => 'ababab'
addHexColor('010101', '010101'); // => '020202'
回答by HBP
How about this:
这个怎么样:
var hexValue = "aaaaaa";
hexValue = (parseInt(hexValue, 16) + 0x010101).toString(16);
document.writeln(hexValue); // outputs 'ababab'
There is no need to add the 0x prefix if you use parseInt.
如果使用 parseInt,则无需添加 0x 前缀。
回答by Abubakar101
I think accepted answer is wrong. Hexadecimal color representation is not a linear. But instead, 3 sets of two characters are given to R, G & B.
我认为接受的答案是错误的。十六进制颜色表示不是线性的。但是相反,给 R、G 和 B 分配了 3 组两个字符。
So you can't just add a whole number and expect to RGB to add up correctly.
因此,您不能只添加一个整数并期望 RGB 正确添加。
For Example
n1 = '005500'; <--- green
n2 = '00ff00'; <--- brighter green
Adding these numbers should result in a greener green. In no way, adding greens should increase RED to increase. but by doing what accepted answer is doing, as in just treat whole number as one number then you'd carry over for numbers adding upto greater than f, f+1 = 10.
添加这些数字应该会产生更绿的绿色。无论如何,添加绿色应该增加红色以增加。但是通过做公认的答案正在做的事情,就像将整数视为一个数字一样,那么您将结转大于 f,f+1 = 10 的数字。
you get `015400` so by adding greens the RED increased .... WRONG
adding 005500 + 00ff00 should result in, = 00ff00. You can't add more green to max green.
添加 005500 + 00ff00 应该导致 = 00ff00。您不能在最大绿色中添加更多绿色。
回答by KFox112
For folks looking for a function that can add and subtract HEX colors without going out of bounds on an individual tuple, I wrote this function a few minutes ago to do just that:
对于正在寻找可以在不超出单个元组范围的情况下添加和减去 HEX 颜色的函数的人,我在几分钟前编写了这个函数来做到这一点:
export function shiftColor(base, change, direction) {
const colorRegEx = /^\#?[A-Fa-f0-9]{6}$/;
// Missing parameter(s)
if (!base || !change) {
return '000000';
}
// Invalid parameter(s)
if (!base.match(colorRegEx) || !change.match(colorRegEx)) {
return '000000';
}
// Remove any '#'s
base = base.replace(/\#/g, '');
change = change.replace(/\#/g, '');
// Build new color
let newColor = '';
for (let i = 0; i < 3; i++) {
const basePiece = parseInt(base.substring(i * 2, i * 2 + 2), 16);
const changePiece = parseInt(change.substring(i * 2, i * 2 + 2), 16);
let newPiece = '';
if (direction === 'add') {
newPiece = (basePiece + changePiece);
newPiece = newPiece > 255 ? 255 : newPiece;
}
if (direction === 'sub') {
newPiece = (basePiece - changePiece);
newPiece = newPiece < 0 ? 0 : newPiece;
}
newPiece = newPiece.toString(16);
newPiece = newPiece.length < 2 ? '0' + newPiece : newPiece;
newColor += newPiece;
}
return newColor;
}
You pass your base color as parameter 1, your change as parameter 2, and then 'add' or 'sub' as the last parameter depending on your intent.
您将基色作为参数 1 传递,将更改作为参数 2 传递,然后根据您的意图将“add”或“sub”作为最后一个参数传递。