html中样式操作

在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

计算的样式

  虽然以上已经可以访问到style,但是不包含外部引用的样式,所以得到的不一定是页面中真正的样式。这里就可以使用计算以后的样式。DOM2级增强了document.defaultView,提供了getComputedStyle()方法,它返回一个CSSStyleDeclaration对象,其中包含当前元素所有计算后的样式,如下:

<html>
    <head>
        <style type="text/css">
            div{
                background-color: black;
            }
        </style>
        <script type="text/javascript">
            window.onload = function(){
                var div = document.getElementsByTagName('div')[0],val,prop,str='',
                stylelist = document.defaultView.getComputedStyle(div,null);
                for(var i = 0,len = stylelist.length;i<len;i++){
                    prop = stylelist.item(i);   //or div.style[i]
                    value = stylelist.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

  在IE中,不支持getComputedStyle,但是有个currentStyle属性,功能类似,即可以用div.currentStyle来返回计算后的样式。

操作样式表

 CSSStyleSheet类型表示的是样式表,包括通过style包裹的样式表和link引入的样式表,使用下面的代码可以看浏览器是否支持DOM2级样式表。

var supportDOM2StyleSheets = document.implementation.hasFeature('StyleSheets','2.0');

  这里主要介绍几个StyleSheet属性和方法:

     disabled:表示样式表是否被禁用的布尔值,可读写,设置为true后就会禁用该样式表。

     type:表示样式表类型的字符串,只读

     cssRules:样式表中包含的样式规则的集合,在IE中为rules

     deleteRule(index):删除cssRules集合中指定位置的规则,IE中用removeRule()

     insertRule(rule,index):在cssRules中指定位置添加规则,IE中用addRule()

 同样,在这里还是可以用length和item()来访问,看以下这个例子

 1 <html>
 2     <head>
 3         <style type="text/css">
 4             div{
 5                 background-color: black;
 6             }
 7         </style>
 8         <script type="text/javascript">
 9             window.onload = function(){
10                 var sheet = document.styleSheets[0],
11                 rules = sheet.cssRules || sheet.rules,
12                 rule = rules[0];
13                 console.log(rule.style.cssText);
14                 console.log(rule.style.backgroundColor);
15             }
16         </script>
17     </head>
18     <body>
19         <div style="width:20px;height:20px;font-size:12px;"></div>
20     </body>
21 </html>
View Code

 这里面又包括了一个CSSRule对象,它表示的是每一条规则,其中几个属性的意义如下:

     cssText:返回css规则文本

     selectorText:返回选择符文本

     style:里面是一个CSSStyleDeclaration对象,可以通过它得到规则中特定的键值对

 同时,可以通过insertRule方法插入规则,接受两个参数,分别是规则文本和插入规则的索引,例子如下:

sheet.insertRule("body {background:red;}",0);

在IE8及更早的版本以前,有一个类似的方法,叫addRule(),有两个必选参数,选择符文本、CSS样式信息和一个可选参数—插入规则位置,示例如下:

sheet.addRule('body','background:red;',0);

同样删除规则也是如此,一般为deleteRule,IE支持的是removeRule

function deleteRule(sheet,index){
    if(sheet.deleteRule){
        sheet.deleteRule(index);
    }else if(sheet.removeRule){
        sheet.removeRule(index);
    }
}

这样就可以兼容所有主流浏览器了,通过传入sheet和要删除的CSS规则的索引,就可以删除指定的规则了。

posted @ 2014-02-07 13:29  胖蝎子  阅读(781)  评论(0编辑  收藏  举报