2013-10-28 30 views
0

嗯,我有一個函數來獲取單擊的html元素的背景顏色。然而,當我通過css設置背景顏色時,在類中,x.style.background中的對象背景顏色僅返回「」;獲取Html元素背景顏色與JS

我的代碼: HTML:

<li onclick="setCor(this)" id="vermelho" class="vermelho">Vermelho</li> 

的JS功能:

function setCor(x){ 
    cor = x.style.backgroundColor; 
} 

而且.vermelho類:

.vermelho{ 
    background-color: #ff0000; 
} 

如何通過JS獲得CSS值?我不能使用它的jQuery,只需要JS。

+0

可能的重複[如何從CSS類通過javascript/jquery獲取樣式屬性?](http://stackoverflow.com/questions/16965515/how-to-get-a-style-attribute-from-a -css-class-by-javascript-jquery) –

回答

4

element.style只返回內嵌樣式屬性(在這裏看到:https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style#Notes

你可能會更好使用window.getComputedStyle()。但是,如果您願意,可以返回RGB顏色,您可能想要將其轉換爲十六進制。

function setCor(x) { 
    cor = window.getComputedStyle(x, null)['background-color']; 
} 
+2

getComputedStyle()不是由<= IE8實現的,要在IE中工作,在上面的代碼中添加currentStyle。 –

+0

感謝ComFreek的幫助。還有斯賓塞倫納德。 –

0

只需在@Ixe答案處添加備註即可。從這個傢伙Can I force jQuery.css("backgroundColor") returns on hexadecimal format?採取

的Javascript

function hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2); } 

function toHex(value) { return "#" + hex(value[0]) + hex(value[1]) + hex(value[2]) } 

代碼:

您可能需要使用此功能的值從RGB轉換爲十六進制