JS获得css样式即获得元素的计算样式(《Javascript精粹修订版》书摘)

为HTML文档中的元素指定样式可以有3种方法:使用内嵌样式、在页面的head中对Style进行声明以及外部 CSS 文件。元素的视觉效果往往是由上述3种方式的结合或者其中某一种方式来确定的,但是内嵌样式通过元素的 Style 对象来访问,而其他的方式,相对应的style 对象属性将是空值。元素的计算样式包括了所有元素可以应用的样式。这些计算样式都可以通过javascript 访问,不过不是使用style 对象,而是需要更多一点的代码才能访问到他们。下面提供的代码就可以做到这些:
<div id="container" style="width:500px;cursor:pointer;">获得元素的计算样式</div>在 W3C DOM下,元素的计算样式可以通过 document.defaultView 并借助 getComputedStyle 方法来访问,代码如下:
var heading = document.getElementById("container");
var computedStyle = document.defaultView.getComputedStyle(heading,null);
var computedFontSize = computedStyle.fontSize;
alert(computedFontSize);而在 IE 中方法更简单一下,借助元素特有的属性 currentStyle便可以访问到计算样式了,代码如下:
var heading = document.getElementById('container');
var computedFontSize = heading.currentStyle.fontSize;
alert(computedFontSize);
综合上述的方法,我们给出了一个跨浏览器的计算样式的函数,代码如下:
function retrieveComputedStyle(element,styleProperty){
   var computedStyle = null;
   if (typeof element.currentStyle != 'undefined'){
        computedStyle = element.currentStyle;
   }else{
        computedStyle = document.defaultView.getComputedStyle(element,null);
   }
   return computedStyle[styleProperty];
}

var heading = document.getElementById("container");
alert(retrieveComputedStyle(heading,"fontSize"));
虽然该方法能得到元素的样式,不过在不同的浏览器下,返回值可能不一样。这点要一定要注意,特别是在样式没有定义的情况。比如上面的例子中Firefox 返回 16px,而在 IE 中返回 12pt

posted @ 2014-04-17 10:59  nan  阅读(211)  评论(0编辑  收藏  举报