2014-10-31 121 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

相關問題