我从dom元素中获得"rgb(18,115,224)“。现在,我想将颜色(无论从这个元素中得到什么)分配给span元素。所以我需要与我所得到的颜色相当的十六进制。为此,我可以用
"#" + componentToHex(r) + componentToHex(g) + componentToHex(b)但是,我的问题是如何从"rgb(18,115,224)“中得到r,g,b组件的值。
发布于 2014-10-31 16:36:51
现在,我想将颜色(无论从这个元素中得到什么)分配给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);
}
这允许我们忽略第四个(alpha)参数的可能性。
发布于 2014-10-31 16:37:13
你不需要把它转换成任何东西。如果要将此值赋给span颜色,则只需:
var clr = "rgb(18, 115, 224)";
$('#myspan').css('color', clr);https://stackoverflow.com/questions/26679366
复制相似问题