카테고리 없음
inline style이 아닌 다른방법으로 지정된 엘리먼트의 CSS 알아내기
나를찾는아이
2007. 11. 9. 10:36
728x90
반응형
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>inline style이 아닌 다른 방법으로 엘리먼트에 적용된 style 알아내기</title>
<style type="text/css">
#tar {
width:350px;
height:50px;
padding:50px 20px 10px 30px;
margin:0px 5px 10px 15px;
background:red;
}
</style>
<script type="text/javascript">
function getStyle(element, style){
if(element.currentStyle) return element.currentStyle.getAttribute(style); // IE
else{
var css = document.defaultView.getComputedStyle(element, null);
return css.getPropertyValue(style);
}
}
</script>
</head>
<body>
<div id="tar">값을 알고자 하는 엘리먼트<br />
#tar {<br />
width:70px;<br />
height:50px;<br />
padding:50px 20px 10px 30px;<br />
margin:0px 5px 10px 15px;<br />
background:red;<br />
}
</div>
<ul>
<li><a href="#tar" onclick="alert(getStyle(document.getElementById('tar'), 'display'));return false;">특별한 값이 지정되어있지 않은 display</a></li>
<li><a href="#tar" onclick="alert(getStyle(document.getElementById('tar'), 'padding'));return false;">여러개의 값이 들어있는 padding</a></li>
<li><a href="#tar" onclick="alert(getStyle(document.getElementById('tar'), 'backgroundColor'));return false;">background-color만 지정된 background</a></li>
<li><a href="#tar" onclick="alert(getStyle(document.getElementById('tar'), 'width'));return false;">값이 정해져있는 width</a></li>
</ul>
</body>
</html>
function getStyle(element, style){
if(element.currentStyle) return element.currentStyle.getAttribute(style); // IE
else{
var css = document.defaultView.getComputedStyle(element, null);
return css.getPropertyValue(style);
}
}
함수는 첫번재 인자로 엘리먼트, 두번재 인자로 알고자하는 CSS 속성명입니다.
IE는 currentStyle로 판별할수 있고 그외의 브라우저는 표준인 getComputedStyle로 알아낼수 있습니다.
하지만 사용하기 좀 난감한 것은 위의 예제를 여러브라우저에서 실행보시면 알수 있듯이 브라우저마다 리턴값이 틀린 경우가 많습니다.
속편하게 인라인으로........고고싱.
관련레퍼런스 :
http://developer.mozilla.org/en/docs/DOM:window.getComputedStyle
http://msdn2.microsoft.com/en-us/library/ms535231.aspx
728x90
반응형