En realidad lo intenté Charlie Kilian's answer. Por alguna razón, no funcionó cuando intentas configurar .css('color')
con un valor 'rgb (0,0,0)'.
No sé por qué. Funcionó perfectamente en la consola. Tal vez fue porque mi función de comparación está en un objeto javascript y es algún tipo de problema de contexto o de referencia. De cualquier manera, finalmente me frustré y escribí mi propia función que comparará dos colores, independientemente de los formatos, y no creará ningún elemento ni dependerá de jQuery. La función toma valores HEX y RGB.
Probablemente se puede optimizar, pero realmente no tengo el tiempo ahora. Espero que esto ayude a alguien es javascript puro.
var compareColors= function (left, right) {
var l= parseColor(left);
var r=parseColor(right);
if(l !=null && r!=null){
return l.r == r.r && l.g == r.g && l.b == r.b;
}else{
return false;
}
function parseColor(color){
if(color.length==6 || color.length==7){
//hex color
return {
r:hexToR(color),
g:hexToG(color),
b:hexToB(color)
}
}else if(color.toLowerCase().indexOf('rgb')>-1){
var arr
var re = /\s*[0-9]{1,3}\s*,\s*[0-9]{1,3}\s*,\s*[0-9]{1,3}\s*/gmi;
var m;
if ((m = re.exec(color)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
arr = m[0].split(',');
return {
r: parseInt(arr[0].trim()),
g: parseInt(arr[1].trim()),
b: parseInt(arr[2].trim())
}
}else{
return null;
}
} else{
return null;
}
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
}
}
Estas funciones siguientes me tomaron de www.javascripter.net
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
¿Qué desea comparar? Brillo, tono, saturación? ¿Cual es tu meta? –
Necesito saber si el campo de texto tiene datos reales. porque ahora tiene una etiqueta en un color diferente que cuando el usuario realmente ha invocado algo ... – newbie