2014-10-31 94 views
0

我从dom元素中获得“rgb(18,115,224)”。现在我想将颜色(无论我从这个元素得到)分配给一个span元素。所以我需要相当于我得到的颜色的十六进制。为此,我可以使用获取r,g,b中rgb()格式的颜色分量

"#" + componentToHex(r) + componentToHex(g) + componentToHex(b) 

但是,在这里我的问题是我如何能得到的R,G,从 “RGB(18,115,224),” B成分值

+0

UM,为什么你不能只分配rgb?作业不必以十六进制完成。 – epascarello 2014-10-31 16:36:53

回答

2

现在我想将颜色(无论我从这个元素获得)分配给一个span元素。

不,你可以直接使用rgb(18, 115, 224)为CSS中的颜色值。 (但请参阅下面如何获得六角如果你真的需要它。)无偿例如:

$("#the-span").css("color", "rgb(18, 115, 224)");
<span id="the-span">I'm the span</span>

或者没有jQuery的,只是其他人谁发现这个以后:

document.getElementById("the-span").style.color = "rgb(18, 115, 224)";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<span id="the-span">I'm the span</span>


但是让我们假设你需要六角因为某些原因:

function getRGB(str) { 
 
    var result = /rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*\d+\s*)?\)/.exec(str); 
 
    if (result) { 
 
     return "#" + 
 
       toHex(+result[1], 2) + 
 
       toHex(+result[2], 2) + 
 
       toHex(+result[3], 2); 
 
    } 
 
    return undefined; 
 
} 
 

 
// Note that this is a simplistic toHex appropriate only for this, not negatives or fractionals 
 
function toHex(num, min) { 
 
    var hex = num.toString(16); 
 
    while (hex.length < (min || 0)) { 
 
     hex = "0" + hex; 
 
    } 
 
    return hex; 
 
} 
 

 
function test(str) { 
 
    display(str + " => " + getRGB(str)); 
 
} 
 

 
test("rgb(18, 115, 224)"); 
 
test("rgb(18, 115, 224, 50)"); 
 

 
function display(msg) { 
 
    var p = document.createElement('p'); 
 
    p.innerHTML = String(msg); 
 
    document.body.appendChild(p); 
 
}

允许第四(阿尔法)的说法,这是我们忽略的可能性。

1

你不需要把它转换成任何东西。如果你想把这个值赋给一个span颜色,那么简单地做:

var clr = "rgb(18, 115, 224)"; 
$('#myspan').css('color', clr); 
+0

而这将是一个错误。缺少引号,做出了改变。 – epascarello 2014-10-31 16:37:34

+0

这是假设jQuery。 – phantom 2014-10-31 16:37:38

+2

@phantom:问题被标记为“jquery”。 – 2014-10-31 16:38:17