在HTML中使用样式有三种方式,link引入、style中编写和元素中定义具体style。DOM2对这三种提供了一系列API,要确定是否可以使用这些方法,可以用以下代码判断:

var isSupportDom2CSS = document.implementation.hasFeature("CSS","2.0");
var isSupportDom2Css2 = document.implementation.hasFeature("CSS2","2.0");

访问元素的样式

  支持style的元素都会含有一个style的属性,这个属性石CSSStyleDeclaration的实例,包含着由元素里定义的所有css样式信息,但是不包含由style定义的css和外部引入的css规则。对于中间有短横的属性,如background-color,需把它转化为驼峰命名法,即backgroundColor。

  多数情况下都是这样转换的,唯一一个特殊的就是float,因为它是javascript的保留字,不能用作属性名,所以DOM2级样式规定该属性名应该是cssFloat,IE中用的是styleFloat。

<html>
    <head>
        <script type="text/javascript">
            window.onload = function(){
                var div = document.getElementsByTagName('div')[0];
                console.log(div.style.width);                         //20px
                console.log(div.style.height);                        //20px
                console.log(div.style.fontSize);                      //12px
            }
        </script>
    </head>
    <body>
        <div style="width:20px;height:20px;font-size:12px;"></div>
    </body>
</html>

DOM2级样式还为style对象定义了一系列属性和方法,这些属性和方法可以实现元素样式的读写功能,属性方法如下:

  cssText:访问style中的css代码;

      length:应用给元素的css属性的数量;

      getPropertyCSSValue(propertyName): 根据属性名字得到属性对象;

      getPropertyPriority(propertyName):根据属性名字得到属性的优先权,即是否使用了important

      getPropertyValue(propertyName):得到指定属性名字的属性值

      item(index):给定位置的css属性名称;

  以上只是一部分比较常用的属性方法。

  其中cssText可以读写当前元素的css样式,直接对cssText赋值就可以重写原有style。

  length和item的出现主要是为了遍历元素中所定义的style属性,当然,也可以用方括号来替换item来访问style,它们都取得的是css的属性名,然后用getPropertyValue来访问属性值,代码如下:

<html>
    <head>
        <script type="text/javascript">
            window.onload = function(){
                var div = document.getElementsByTagName('div')[0],val,prop,str='';
                for(var i = 0,len = div.style.length;i<len;i++){
                    prop = div.style.item(i);   //or div.style[i]
                    value = div.style.getPropertyValue(prop);
                    str += (prop +' : ' + value + ';');
                }
                console.log(str);
            }
        </script>
    </head>
    <body>
        <div style="width:20px;height:20px;font-size:12px;"></div>
    </body>
</html>
View Code

相关文章: