2012-02-16 60 views
1

我希望能夠從未在網頁上使用的CSS元素獲取樣式。例如,這是頁面:Javascript獲取CSS樣式爲ID

<html> 
<head> 
<style type="text/css"> 
#custom{ 
background-color: #000; 
} 
</style> 
</head> 

<body> 
<p>Hello world</p> 
</body> 
</html> 

正如您所看到的ID'custom'有一個值,但未在文檔中使用。我想在頁面中使用「自定義」的所有值。我來最接近的是:

el = document.getElementById('custom'); 
var result; 
var styleProp = 'background-color'; 
if(el.currentStyle){ 
    result = el.currentStyle[styleProp]; 
    }else if (window.getComputedStyle){ 
    result = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp); 
    }else{ 
    result = "unknown"; 
} 
+1

有沒有你想重新實現CSS類特殊的原因?請告訴我們你最終的結果是什麼,我們可以幫助你達到目標。 – 2012-02-16 12:26:40

回答

5

創建元素,並將其添加到文檔中,暫時:

var result, 
    el = document.body.appendChild(document.createElement("div")), 
    styleProp = 'background-color', 
    style; 

el.id = 'custom'; 
style = el.currentStyle || window.getComputedStyle(el, null); 
result = el[styleProp] || "unknown"; 

// Remove the element 
document.body.removeChild(el);