This article presents JavaScript and PHP functions for converting RGB color values to hexadecimal (hex) values and vice-versa. This is particularly useful when dynamically manipulating HTML colors using jQuery.
RGB to Hex Conversion (JavaScript - Method 1):
function rgb2hex(rgb){ rgb = rgb.match(/^rgb\((\d+),(\d+),(\d+)\)$/); return "#" + ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[3],10).toString(16)).slice(-2); }
RGB to Hex Conversion (JavaScript - Method 2):
This method uses helper functions for better readability and maintainability.
function RGB2Color(r,g,b) { return '#' + byte2Hex(r) + byte2Hex(g) + byte2Hex(b); } function byte2Hex (n) { var nybHexString = "0123456789ABCDEF"; return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1); }
Hex to RGB Conversion (JavaScript):
This function needs improvement to correctly handle the g
component.
function hexToRgb(h) { var r = parseInt((cutHex(h)).substring(0,2),16); var g = parseInt((cutHex(h)).substring(2,4),16); var b = parseInt((cutHex(h)).substring(4,6),16); return r + ',' + g + ',' + b; //Corrected return statement } function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h} //usage console.log(hexToRgb("#FFFFFF"));
Hex to RGB Conversion (PHP):
function hex2rgb( $colour ) { if ( $colour[0] == '#' ) { $colour = substr( $colour, 1 ); } if ( strlen( $colour ) == 6 ) { list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] ); } elseif ( strlen( $colour ) == 3 ) { list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] ); } else { return false; } $r = hexdec( $r ); $g = hexdec( $g ); $b = hexdec( $b ); return array( 'red' => $r, 'green' => $g, 'blue' => $b ); }
Frequently Asked Questions (FAQs):
The FAQs section remains largely unchanged, as the information provided is accurate and relevant. Consider adding examples of how to use the provided functions within a jQuery context to enhance the practical value of the article.
The above is the detailed content of jQuery Convert RGB to Hex Colour Values. For more information, please follow other related articles on the PHP Chinese website!