2012-02-16 3 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는 값이 있지만 문서에는 사용되지 않은 것을 볼 수 있습니다. 나는 페이지에서 그것을 사용하지 않고 '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

있습니까? 최종 결과를 원하는대로 알려 주시면 도움을 드릴 수 있습니다. –

답변

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); 
관련 문제