■ 프론트엔드 ■/JavaScript
rgb를 16 진수로
serpiko
2017. 3. 20. 16:26
rgb를 16진수로
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | (by Matt) function rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); function hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2); } return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } * 일부 브라우저에서는 이미 16 진수 색상이 반환된다. (예를들어 Internet Explorer 8 이상). 그런 경우에 대처할 필요가있는 경우 함수에 조건을 추가하면된다 (by gfrobenius) function rgb2hex(rgb) { if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb; rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); function hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2); } return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } | cs |