2008년 1월 13일 일요일

특정 element의 css 스타일 속성을 얻어오기

function getStyle(elementID, propertyName)
{
// 1. element를 얻어옵니다.
var element = document.getElementById(elementID);

// 2-1. ie인 경우
if (element.currentStyle)
{
// 2-2. currentStyle 속성을 이용하여서 propertyValue를 얻어옵니다.
var propertyValue = element.currentStyle[propertyName];
}
// 3-1. Firefox, Opera 등의 경우
else if (window.getComputedStyle)
{
// 3-2. element에 적용된 CSS 스타일들(CSSStyleDeclaration object)을 얻어옵니다.
var computedStyle = document.defaultView.getComputedStyle(element,null);

// 3-3. 속성 이름을 인자로 넘겨서 propertyValue를 받아옵니다.
var propertyValue = computedStyle.getPropertyValue(propertyName);
}
return propertyValue;
}
quirksmode.org에 소개되어 있는 특정 element의 style 속성 값을 얻어오는 함수입니다.
  • IE의 경우 currentStyle 속성을 이용해서 값을 얻어오고
  • Firefox나 Opera의 경우에는 getComputedStyle을 이용해서 값을 얻어옵니다.
출처: Quirksmode.org - Get Styles

P.S> 어쩌다 yagne.com의 yag_lib.js를 보게 되었습니다. getStyle과 같이 element의 style의 특정 속성을 가지고 올 때,
  1. 가장 먼저보는 곳이 element.style[property]를 살피고
  2. 그 다음 처리가, element.currentStyle
  3. 그리고 window.getComputedStyle을 호출하네요.
var camel = YOB_String.camelize(property);
if (ele.style[camel]) {
    return ele.style[camel] || null;
}
else if (ele.currentStyle) {
    return ele.currentStyle[camel] || null;
}
else if (document.defaultView && document.defaultView.getComputedStyle) {
    return document.defaultView.getComputedStyle(ele, null).getPropertyValue(property) || null;
}
else {
    return null;
}
element.style[property]에 설정되는 값은 CSS 적용 룰에서 최우선적으로 적용되기 때문에 2,3의 코드를 탈 필요도 없이 바로 확인이 가능하겠죠.
Element.Methods = {
    getStyle: function(element, style) {
        ...
        var value = element.style[style];
        if (!value) {
            var css = document.defaultView.getComputedStyle(element, null);
            value = css ? css[style] : null;
        }
        ...
    },
}

if (Prototype.Browser.Opera) {
    Element.Methods._getStyle = Element.Methods.getStyle;
        ...
    };
}
else if (Prototype.Browser.IE) {
    Element.Methods.getStyle = function(element, style) {
        ...
        var value = element.style[style];
        if (!value && element.currentStyle) value = element.currentStyle[style];       
    };
}else if (Prototype.Browser.Gecko) {
  Element.Methods.setOpacity = function(element, value) {
  };
}
prototype도 동일하게 되어있네요. 다른 점은 2,3의 코드를 로딩타임에 브라우져 별로 분리하여서 로딩하네요.

댓글 2개:

  1. 잘 읽고 갑니다. 관련해서 보고 있었는데

    내용과 URL이 도움이 되었습니다. ^^

    답글삭제