2016-03-25 10 views
1

Jetzt bekomme ich ein Objekt, das eine Farbe namens 'Clear' enthält. Ich möchte es auf RGB-Wert setzen, und ich habe eine Funktion, um dies zu tun, aber es gibt mir 'rgb (51, 51, 51)', während in angular chorme Diagramm es auf '# 3366cc'resolove es auf. Wie kann ich Holen Sie den rgb-Wert ohne Verwendung anderer js-Bibliotheken? -Wie wird die Farbe 'Clear' auf RGB oder HEX gesetzt?


function(){ 
    var div = document.createElement('div'); 
    var rgbColor; 
    div.style.color = 'Clear'; 
    document.body.appendChild(div); 
    rgbColor = window.getComputedStyle(div).color 
    div.remove(); 
    return rgbColor; 
} 
+0

http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb – Sagi

Antwort

0
function componentToHex(c) { 
    var hex = c.toString(16); 
    return hex.length == 1 ? "0" + hex : hex; 
} 

function rgbToHex(r, g, b) { 
    return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); 
} 

function getColor(){ 
    var r = 0; 
    var g = 0; 
    var b = 0; 
    var rgbColor; 
    var div = document.createElement('div'); 

    div.style.color = 'Clear'; 
    document.body.appendChild(div); 
    rgbColor = window.getComputedStyle(div).color 
    var matches = div.style.color.match(/^rgb\((\d+), (\d+), (\d+)\)$/); 

    if (matches) { 
     r = parseInt(matches[1]); 
     g = parseInt(matches[2]); 
     b = parseInt(matches[3]); 
    } 
    div.remove(); 
    return rgbToHex(r, g, b); 
}