2012-02-16 10 views
1

ウェブページで使用されていないCSS要素からスタイルを取得したいと考えています。たとえば、このページです:JavascriptがID用のCSSスタイルを取得

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

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

あなたはID「カスタム」の値を持っていますが、文書内で使用されていない見ることができるように。私はそのページでそれを使わずに 'カスタム'のすべての値を取得したいと思います。私が来た最も近いです:

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

ありますか?最終結果が欲しいものがあれば教えてください。そして、あなたがそこに着く手助けをすることができます。 –

答えて

5

は、要素を作成し、それは一時的に、文書に追加:あなたはCSSクラスを再実装しようとしている特定の理由が

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);