因为写js经常需要用到访问样式,我们常用的做法是通过 DOM.style.XXX来读写样式信息的。可是DOM.style这种写法只能访问,这样在标签里内置的样式,如果样式写在,或者.css文件里,那么就办法读到样式了。
其实呢,还有别的方法可以读到这些样式信息,方法有两种,一种是通过document.styleSheets对象,另一种是通过“最终样式”对象。其中 IE中这个对象叫做currentStyle,FF中这个对象叫做document.defaultView。
我采用的代码(没有YUI的精确,但基本够用)
其实呢,还有别的方法可以读到这些样式信息,方法有两种,一种是通过document.styleSheets对象,另一种是通过“最终样式”对象。其中 IE中这个对象叫做currentStyle,FF中这个对象叫做document.defaultView。
我采用的代码(没有YUI的精确,但基本够用)
getComputedStyle: function(elm, styleName) {
elm = Y.$(elm);
if( window.getComputedStyle ) {
return elm.ownerDocument.defaultView.getComputedStyle(elm, null)[styleName]; // window.getComputedStyle(elm, null)[styleName];
} else if( elm.currentStyle ) {
return elm.currentStyle[styleName];
}
}