Search

12/19/2007

Computed vs Cascaded Style

Computed vs Cascaded Style

function getStyle(el, prop) {
if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el, null)[prop];
} else if (el.currentStyle) {
return el.currentStyle[prop];
} else {
return el.style[prop];
}
}

So what is wrong with this you might ask?.

div { width: 500px; font-size: 12px; }
p { width: 50%; font-size: 1em; }
a { font-size: inherit; }

<div>
<p id="p">Some text with <a id=a href=#>a link</a>.
More <b style="font-size:150%">text</b></p>
</div>


alert(getStyle(document.getElementById('p'), 'fontSize'));
//ie:1em(cascaded style) ff: 12px(computed style)

alert(getStyle(document.getElementById('p'), 'width'));
//ie:50%(cascaded style) ff:250px(computed style)

All browsers except IE has a way to get the computed style. The way to do
this is to use document.defaultView.getComputedStyle. Only IE has a way to get
the cascaded style. This is done using element.currentStyle.

沒有留言: