zoukankan      html  css  js  c++  java
  • css样式获取,style,currentStyle,getComputedStyle

    对于css样式的获取问题,对于行内样式,我们可以用style来获取,但是对于内嵌和外部样式的话,style就心有余和力不足了。它是获取不到这些样式的

    此时就只有currentStyle和getComputedStyle上阵了。

    currentStyle是只兼容各种IE的,但是不兼容火狐,谷歌的,而getComputeStyle的话是可以兼容火狐,谷歌,和IE9+的。(以下测试均在谷歌和IE下)

    对于行内样式:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <!-- <link href="test.css" rel="stylesheet"> -->
        <script type="text/javascript" src="test.js" defer="defer"></script>
        <title>Document</title>
    </head>
    <style type="text/css">
    </style>
    <body>
        <div class="wrap" style="
        100px;
        height:100px;
        background-color:black;">
        </div>
    </body>
    </html>

    此时用这着三种方法:

    var oWrap = document.getElementsByTagName("div")[0];
    window.onload = function (){
        console.log(oWrap.style.width);
        console.log(oWrap.currentStyle.width);
        console.log(getComputedStyle(oWrap,null).width);
    }

    得到的结果是:

    把报错的,也就是currentStyle注释掉,就会得到:

    情理之中。因为currentStyle时不兼容谷歌的

     然后改成内嵌样式的话:

    结果也在意料之中:

    再加上注释了,结果是:

    外部样式表的话,结果也是一样的。

    然后IE的话,

    IE8的话是不支持getComputedStyle。而IE9+是支持的。

    外部样式IE8:

    外部样式IE9:

     

    最后完全符合结果。

    结论:

    1.style只支持行内样式,对于其他样式引入方式一律不好用。

    2.currentStyle和getComputedStyle支持各种样式引入方式。但存在兼容性问题。

    3.currentStyle兼容IE,不兼容谷歌,火狐等浏览器,会报错。

    4.getComputedStyle兼容谷歌,火狐,IE9+,不兼容IE8以下,包括IE8。

    注意:

    1.currentStyle的使用方式是:元素.currentStyle("样式名")或者元素.currentStyle.样式名。

    2.getComputedStyle是全局的,使用方式是:getComputedStyle("元素",“伪类”)["样式名"]或者getComputedStyle("元素",“伪类”).样式名。

  • 相关阅读:
    Win32.Dfcsvc.A
    清除“熊猫烧香”(Worm.WhBoy.h、尼姆亚、FuckJacks)
    个人网站如何提高网站的Google PR值
    ROSE病毒
    vc二进制数值字符相互转换
    全flash站制作剖析
    C#.NET 中的类型转换
    .net开发常用工具
    xflash里的hello world程序
    什么是XHTML
  • 原文地址:https://www.cnblogs.com/178-533/p/7783944.html
Copyright © 2011-2022 走看看