Created
June 3, 2014 01:13
-
-
Save jikeytang/1ca86ae1bf29e41ed179 to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140603-题目1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
如何将颜色值十六进制,RGB相互转换? | |
如:#ffffff转换为:RGB(255,255,255) | |
RGB(23, 245, 56)转换为:#17f538 | |
PS: | |
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。 | |
```javascript | |
// you code | |
``` | |
2. 粘贴代码时请使用shift+tab,缩进前面的空白。 |
rambo-panda
commented
Jun 3, 2014
function convert(str) {
var rhex = /\#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/;
var rrgb = /RGB\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;
var rblank = /\s*/g;
var match;
str = str ? str.replace(rblank, '') : '';
if(match = str.match(rhex)) {
return toRGB(match);
} else if(match = str.match(rrgb)) {
return toHex(match);
} else {
throw Error('Invalid format.');
}
}
function toHex(rgb) {
var result = '';
var item;
for(var i = 1; i <= 3; i++) {
item = +rgb[i];
result += '0'.substring(Math.floor(item / 16)) + item.toString(16);
}
return '#' + result;
}
function toRGB(hex) {
var result = '';
for(var i = 1; i <= 3; i++) {
result += parseInt(hex[i], 16) + ',';
}
return 'RGB(' + result.substring(0, result.length - 1) + ')';
}
console.log(convert('#172dff'));
console.log(convert('RGB(2, 45, 255)'));
建议考虑一下#333和#FFF的情况
"#" + "RGB(23, 245, 56)".match(/\d+/g).map(function(num){ return (num-0).toString(16) }).join("");
"RGB(" + "#17f538".match(/\w{2}/g).map(function(str){ return parseInt(str, 16)}).join(",") + ")";
function pInt(s, mag) {
return parseInt(s, mag || 10);
}
function init(input) {
// declare variables
var rgba = [], result;
// rgba
if((result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(input))) {
rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
}
// hex
else if((result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input))) {
rgba = [pInt(result[1],16), pInt(result[2],16), pInt(result[3],16), 1];
}
}
呵呵 一道面试题
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment