zoukankan      html  css  js  c++  java
  • DOM Style样式对象的详细用法

    DOM Style样式对象的详细用法

    HTML Style样式比较复杂,相应访问、修改方法也有所差异。参考相关资料,整理如下。

    典型Html文件如下,有三种定义方式。

    <head>
        <style type="text/css">
                   /* 内部样式 */
          h3 {color:green;}
        </style>
                <!-- 外部样式 style.css -->
        <link rel="stylesheet" type="text/css" href="style.css"/>
               <!-- 在外部的styles.css文件中,代码如下:
                   h3 {color:blue;} -->
    </head>
    <body>
        <h3 style ="color:Black;" >测试!</h3>
    </body>

    定义1:行内样式, (内联样式)Inline style

      任何HTML元素标签都会有一个通用的属性style。它会返回CSSStyleDeclaration对象。

    样式定义在HTML元素的标准属性style里

    a 将分号『;』隔开的一个或者多个属性:值(其全部为元素的style属性的值)

    b 属性和属性值之间用 『:』连接
    下面我们看几个最常见的行内style样式的访问方式。Style在元素节点内,style可读可写;

    <div id='St1' style="font-family:Arial,Helvetica;100px; height:100px; color:red;">芒果</div> 

    var oV1 = document.getElementById('St1')

    a)获取:x = oV1.Style.width

            x = oV1.Style.getPropertyValue('height')

    b)设置:oV1.style.backgroundColor = 'red';

         oV1.Style.setProperty('height', '200px')

    c)移出(2种):oV1.style.font-family="";
             oV1.style.removeProperty("background-color")

    d)所有内联样式 CSS 属性

    style样式是个 CSSStyleDeclaration 对象,它不仅提供了单个 CSS 属性的访问方式,如cssText属性 ,也提供 setProperty()、getPropertyValue()及removeProperty() 方法

      oV1.Style.cssText = "background-color:red; height:200px; 200px"

      oV1.Style.cssText = '';

      oV1.setAttribute('style', 'background-color:blue; height:100px; 100px');

      oV1.getAttribute('style');

      oV1.removeAttribute('style');

      仅能操作style属性中定义的内联样式,无法获取或设置样式表中的样式
     

    定义2:内部样式表(style元素) Internal style sheet

    其使用 <style> 标记将样式定义为内部块对象,内部样式只对所在的网页有效。

    示例代码如下: 嵌入 CSS 可以有效减少 HTTP 请求,提升页面性能
    <head>

    <style type="text/css">
         <!--

          //div(选择器)  { 100px;(样式声明) }
           div,h3 { background-color: black; 100px; }                   //两个标签选择

         #Id1   { 100px; height: 100px; background-color: red; }       //一个id选择符
           .c3    { color:blue;}                                                //class选择符
           p.cla4 { color:#fff; background:#070;}                            /* 一个元素、一个class选择符

         -->

    </style>

    <style type="text/css">  @import url(sty2.css); </style>            //导入式

    <link rel="stylesheet" type="text/css"  href="wider.css">            //外部链接式(rel,type不要动)
    </head>
          //wider.css中的定义   #box { 200px; }


    function getStyle(oDiv, attr){
        if (oDiv.currentStyle)  {return oDiv.currentStyle[attr];              //针对IE浏览器 }
        else                    {return getComputedStyle(oDiv, false)[attr]; }  //Firefox浏览器
        }
    <div id="id1"  class="c3" >test style</div>
    var oT1 = document.getElementById('id1');
    var a = getStyle(oT1, 'width');

      使用style属性可以设置行内的CSS样式,而通过id和class调用时最常用的方法。

      CSSStyleSheet类型表示通过<link>元素(HTMLLinkElement对象)和<style>元素(HTMLStyleElement对象)包含的样式表。
    样式表中一个大括号就是一个cssRule对象
    var sheet=link.sheet||link.styleSheet;    //(非IE)使用sheet属性,(IE)使用styleSheet得到这个类型
    var sheet=document.styleSheets[i];        //styleSheets: 获得当前网页的所有样式表对象

     

    定义3:外部样式表(引用一个CSS样式表文件)Rules或rules

    (1)  DOM(document对象)对象模型中有几个重要的集合 

    doc1.images         [HTMLCollection] 所有图像
    doc1.anchors        [HTMLCollection] 所有锚点
    doc1.styleSheets  [StyleSheetList] 所有样式
    doc1.links          [HTMLCollection] 所有链接

    其中styleSheets包含所有的样式集合

    (2) 样式表集合styleSheets -> 规则(选择器及样式)(css)rules ->某一样式.属性 style.attr

    一个style元素标签(一个样式表var sheet=document.styleSheets[0]

    规则集合(选择器及样式集合)   vsr Rules =sheet.cssRules||sheet[0].rules;   //W3C用cssRules //微软rules

    第一个规则(选择器及样式)     var rule=doc1.styleSheets[0].rules[0]   //rules[0](IE),CSSRules[0](非IE)

                                                  var rule=sheet.cssRules[0]|| sheet.rules[0];

    style标签或单个Style的全部内容  head.style.cssText, oV1.style.cssText 或 rules[0].style.cssText      

    style标签中一个大括号就是一个(css)Rule对象,cssRules(非IE)|rules(IE)可返回某一样式表中全部选择器的集合列表,可以通过CSSRules[0](非IE)和rules[0]属性(IE)来进行访问。第一条规则就是(css)Rules[0],第二条就是(css)Rules[1]等等。

    一条规则就是一个元素的声明 p {background-color: #ffffff;} 或者多个元素的一组声明 div,h3,p{color:blue; 100px;} (IE还将其分为3条)。可以对每个样式进行具体的操作(可读可写)。

        
        通过 className 修改样式 ,  获取或修改某个属性的值(兼容性问题)
    doc1.styleSheets[0].(css)rules[index].style.attr     //IE,W3C为(css),查找样式表中的样式属性(ie chrom)
     

    (3) style样式,规则(css)rules在各浏览器中差异

    例:下列样式表在不同浏览器的解释

    @import url("test.css");
      p,h2,h3 {padding-right: 10px; }
      pre.test + * {margin-right: 20%;  }
      pre.test {background-color: #ffffff; }
     
    Safari看见的是【4条】规则: 注意大写
    cssRules[0]、undefined
    cssRules[1]、P
    cssRules[2]、PRE.test[CLASSS~="test"]+*
    cssRules[3]、PRE.test[CLASSS~="test"]

    Safari则只取p。我才知道这是一种不正确的写法

    IE7看见了【5条】: 注意大写
    rules[0]、P
    rules[1]、H2
    rules[2]、H3
    rules[3]、PRE.test + *
    rules[4]、PRE.test
       IE认为p,h2,h3是三条而不是一条规则,
    Mozilla和Opera 9看见4条: 注意小写
    cssRules[0]、undefined
    cssRules[1]、p,h2,h3
    cssRules[2]、pre.test + *
    cssRules[3]、pre.test
    Mac IE也看见5条: 注意大写
    0、P
    1、H2
    2、H3
    3、PRE.test * (注意没有+号)
    4、PRE.test

    Mac IE把选择器改成了pre.test *,
    这样含义就非常不一样了。非常严重的问题。

    所以要访问pre.test在Safari和Mozilla里需要cssRules[3],而IE是rules[4],早期的Mozilla是cssRules[5]。

    没有关键字 ,所以如果使用索引值的话问题就非常严重。

    我们希望能这样访问: document.styleSheets[1].cssRules['PRE.test'],这样我就能访问pre的样式表规则了。但是W3C或者其他浏览器貌似不需要这样的访问样式表的方法。但是所有的文档在这个问题上都保持沉默。

    这个失败意味着你基本上没法访问规则了。

    假设我们已经访问了一条规则。现在需要改变其中一条声明。

    (1)表达式如下:  rule.style.color = '#0000cc';

    (2)W3C的方法是: rule.style.setProperty('color','#00cc00',null);因为style.color简单的多,所以我不想用这个

    例子:打算改变pre的颜色,代码如下:

    为了保证能用,我把pre的规则写在最后一条。很丑,但是这是唯一的办法:
    function changeIt() {
      if (!document.styleSheets) return;
      var theRules = new Array();
      if (document.styleSheets[1].cssRules)     theRules = document.styleSheets[1].cssRules
      else if (document.styleSheets[1].rules)   theRules = document.styleSheets[1].rules
      else return;
      theRules[theRules.length-1].style.backgroundColor = '#EEF0F5';
      }

    (4) style样式的添加或删除

    doc1.styleSheets[0].insertRule(“selector{attr:value}”, index);     //非IE

    doc1.styleSheets[0].deleteRule(index);                               //非IE

     

    doc1.styleSheets[0].addRule(“selector”,”attr:value”, index);      //IE

    doc1.styleSheets[0].removeRule(index);                               //IE

    a) 插入函数

    function insertRule(sheet,selectorText,cssText,position){
      if(sheet.insertRule){    sheet.insertRule(selectorText+'{'+cssText+'}',position);     }
      else if(sheet.addRule){  sheet.addRule(selectorText,cssText,position);     }

    b) 删除函数

     function deleteRule(sheet,position){ 

      if (sheet.deleteRule)       sheet.deleteRule(position); //非IE ,假设这样的方式存在
      else if(sheet.removeRule){  sheet.removeRule(position);  }

    c) 赋值,改动CSS样式

    rules[0].style.color='green';             //链接CSS样式中改动详细的属性
      oDiv1.style.color='blue';                 //行内样式 

    4 单个操作 或 批量操作

    a) 某元素Style属性的单个操作

    obj.style.backgroundColor="red";  //注意,如果原来样式中有-,需要去掉,然后将后面的单词首字母大写

    b) 某元素Style属性的批量操作

    不仅有单个 CSS 属性的访问方式,如cssText属性 

    doc1.head.style.csstext="h3 {color:green;}"        //网页的Style元素结点内容的修改

    oV1.Style.cssText = "background-color:red; height:200px; 200px"

    oV1.setAttribute('style', 'background-color:blue; height:100px; 100px');

    oV1.removeAttribute('style');

    obj.style="height:500px;color:red;"; //直接设置style对象,注意style的格式

    obj.className="test";          //指定obj的className属性,给它类选择器名                      

    obj.className="test demo";     //使用className设置属性  //注意空格 ,可以指定多个类

    obj.className="";              //删除样式

     

    5 多重样式的计算(Multiple Styles):

    由于外部样式、内部样式和行内样式可能同时作用于某一个元素,此外如DIV,P等元素内部还可能有子元素节点而产生的样式嵌套现象,于是就有了多重样式。

    此种情况下,样式就有了优先级,一般(行内)Inline style  > (内部样式)Internal style sheet >(Css外部样式)External style sheet。有一套比较复杂的计算优先级的方法。

    有个例外的情况,就是如果外部样式放在内部样式的后面,则外部样式将覆盖内部样式。

    对于多种样式的复合情况下真实的样式信息,就需要通过计算,来获得样式,即计算样式(当然也就只读了)。

    原生JS获取CSS样式的方法

    (非IE)window对象下提供了getComputedStyle()方法。接受两个参数,需要计算的样式元素,第二个伪类(:hover),如果没有伪类,就填null。 window.getComputedStyle 还有另一种写法,就是 document.defaultView.getComputedStyle 。

    (IE)使用 currentStyle 属性,IE 中使用 getAttribute 。currentStyle 要获得属性名的话必须采用驼峰式的写法。也就是如果我需要获取 font-size 属性,那么传入的参数应该是 fontSize。因此在IE 中要获得单个属性的值,就必须将属性名转为驼峰形式。

    // IE 下将 CSS 命名转换为驼峰表示法 // font-size --> fontSize // 利用正则处理一下就可以了
    function camelize(attr) {
        // /-(w)/g 正则内的 (w) 是一个捕获,捕获的内容对应后面 function 的 letter
        // 意思是将 匹配到的 -x 结构的 x 转换为大写的 X (x 这里代表任意字母)
        return attr.replace(/-(w)/g, function(all, letter) {
            return letter.toUpperCase();});
      }
    element.currentStyle.getAttribute(camelize(style)); // 获取元素 element 的 style 属性样式
    <style type="text/css">
         <!--
           div { background-color: black; 100px; }
           #id3{ 100px; height: 100px; background-color: red; }

     

     

        -->
    </style>
    <div id='id3'>test style</div>

    function getStyle(oDiv, attr)
        { if (oDiv.currentStyle)
           {return oDiv.currentStyle[attr];                  //IE浏览器 }
          else
           {return getComputedStyle(oDiv, false)[attr]; }  //Firefox浏览器
        }

    var test = document.getElementById('id3');   //得到某元素的样式
      var a = getStyle(test, 'width');

        
    获取最终样式(只能获取,不能操作)
     oDiv1.currentStyle.attr                           // ( IE ) 
     window.getComputedStyle(oDiv1,null).attr          //( W3C )
     

    6 使用脚本添加样式与浏览器的差异

    当在连接外部样式后,再在其后面使用JavaScript 脚本插入内部样式时(即内部样式使用脚本创建),

    <html><head>
      <title> demo </title>  
      <link rel="stylesheet" href="styles.css" type="text/css" />       // <!-- 添加外部CSS 样式 -->
        <!--   在外部的styles.css文件中,代码如下:
            h3 {color:blue;}
        -->      
    <script type="text/javascript">        //  <!-- 使用javascript 创建内部CSS 样式 -->
    <!--
    (function(){
      var agent = window.navigator.userAgent.toLowerCase();
      var is_op = (agent.indexOf("opera") != -1);
      var is_ie = (agent.indexOf("msie") != -1) && document.all && !is_op;
      var is_ch = (agent.indexOf("chrome") != -1);

      var cssStr="h3 {color:green;}";                             //样式
      var s=document.createElement("style");                       //新建<stylr>元素
      var head=document.getElementsByTagName("head").item(0);      //取Head元素
      var link=document.getElementsByTagName("link");              //取Link
      link=link.item(0);

    if (is_ie){
      if (link)   head.insertBefore(s,link);
      else        head.appendChild(s);
      document.styleSheets.item(document.styleSheets.length-1).cssText=cssStr;    //最后一个Style所有内容
      }
    else if(is_ch){
      var tn=document.createTextNode();
      tn.nodeValue=cssStr;
      s.appendChild(tn);                //在IE中非法
      head.insertBefore(s,link);
      }
    else {
      s.innerHTML=cssStr;               //在IE中非法
      head.insertBefore(s,link);
      }
    })();
    //-->
    </script>
    </head> <body>
      <h3>在IE中我是绿色,非IE浏览器下我是蓝色!</h3>
    </body></html>
    结果:在Firefox / Chrome / Safari / Opera 中,文字都是蓝色的。而在IE 浏览器中,文字却是绿色的。
     

  • 相关阅读:
    mac下配置Node.js开发环境、express安装、创建项目
    基于bootstrap模态框的二次封装
    生成二维码、微信自定义分享到朋友圈、ipa不从应用商店安装
    浏览器设备判断
    微信浏览中的下载自动被拦截,加遮罩在浏览其中打开
    css:图标与文字对齐的两种方法
    js获取当前域名
    JS动态修改微信浏览器中的title
    UWP 播放直播流 3MU8
    vb6 读写文件
  • 原文地址:https://www.cnblogs.com/whchensir/p/5743521.html
Copyright © 2011-2022 走看看