style,runtimeStyle与currentStyle的定义及用法

来源:互联网 发布:幼儿创意美工作品图片 编辑:程序博客网 时间:2024/04/29 14:51

1.定义

style:标准的样式!可用来查询由html标签的style属性指定的样式
runtimeStyle: 运行时的样式!如果与style的属性重叠,将覆盖style的属性!
currentStyle:可用来查询/修改外联(由<link>所连接的样式表文件)或者内部(在<style>中的样式)样式表中的样式。

2.举例

<style type="text/css">
<!--
.div2{ width:200px; height:100px; background:#090;}
-->
</style>

 

 

<div id="div2" class="div2" style=" background:#CCC"></div>

<SCRIPT type=text/javascript>
var div=document.getElementById("div2");

alert(div.style.backgroundColor);//ie中输出#ccc,火狐中输出rgb(204,204,204)

alert(div.style.width);//ie中输出为空,火狐中输出为空
alert(div.currentStyle.width);//ie中输出为200px,火狐中无法输出
</SCRIPT>

3.兼容

上例中的最后一个输出语句在ff中无法运行,我们可以添加如下代码让无法运行currentStyle的浏览器可以运行它:

 

<SCRIPT type=text/javascript>
(function (bool) {
    if (bool) {
        HTMLElement.prototype.__defineGetter__("currentStyle", function () {
            return this.ownerDocument.defaultView.getComputedStyle(this, null);
        });
    }
})(!document.body.currentStyle);


</SCRIPT>