zoukankan      html  css  js  c++  java
  • getComputedStyle()与currentStyle

           getComputedStyle()与currentStyle计算元素样式

    发表于 2011-10-27 admin

    “DOM2级样式”增强了document.defaultView,提供了getComputedStyle()方法。这个方法接受 两个参数:要取得计算样式的元素和一个伪元素字符串(例如“:after”)。如果不需要伪元素信息,第二个参数可以是null。 getComputerStyle()方法返回一个CSSStyleDeclaration对象,其中包含当前元素的所有计算的样式。以下面的HTML页 面为例:

    <!DOCTYPE html><html><head><title>计算元素样式</title><style>#myDiv {
        background-color:blue;
        width:100px;
        height:200px;}</style><body><divid="myDiv"style="background-color:red; border:1px solid black"></div><script>
        var myDiv = document.getElementById("myDiv");
        var computedStyle = document.defaultView.getComputedStyle(myDiv,null);
        alert(computedStyle.backgroundColor);    //"red"
        alert(computedStyle.width);              //"100px"
        alert(computedStyle.height);             //"200px"
        alert(computedStyle.border);             //在某些浏览器中是“1px solid black”</script></body></head></html>

    边框属性可能也不会返回样式表中实际的border规则(Opera会返回,但其它浏览器不会)。存在这个差别的原因是不同浏览器解释综合属性的方 式不同,因为设置这种属性实际上会涉及很多其他的属性。在设置border时,实际上是设置了四个边的边框宽度、颜色、样式属性。因此,即使 computedStyle.border不会在所有浏览器中都返回值,但computedStyle.borderLeftWidth则会返回值。

    需要注意的是,即使有些浏览器支持这种功能,但表示值的方式可能会有所区别。例如,Firefox和Safari会返回将所有颜色转换成RGB格式。因此,即使getComputedStyle()方法时,最好多在几种浏览器中测试一下。

    IE不支持getComputedStyle()方法,但它有一种类似的概念。在IE中,每个具有style属性的元素还有一个 currentStyle属性。这个属性是CSSStyleDeclaration的实例,包含当前元素全部计算后的样式。取得这些样式的方法差不多,如 下:

    var myDiv = document.getElementById("myDiv");var computedStyle = myDiv.currentStyle;
    alert(computedStyle.backgroundColor);//"red"
    alert(computedStyle.width);//"100px"
    alert(computedStyle.height);//"200px"
    alert(computedStyle.border);//undefined

    与DOM版本的方式一样,IE也没有返回border样式,因为这是一个综合属性。

  • 相关阅读:
    django报错信息解决办法
    postgresql数据库的基本使用
    Ubuntu 18.04中安装PostgreSQL(PSQL)
    Ubuntu 18.04 安装 PyCharm
    在Ubuntu中安装Docker和docker的使用
    ubuntu怎么切换到root用户,切换到root账号方法
    centos7彻底卸载mysql和通过yum安装mysql
    django运行时报错处理方法
    Django 查询时间段 时间搜索 过滤
    View Controller Programming Guide for iOS---(四)---Creating Custom Content View Controllers
  • 原文地址:https://www.cnblogs.com/rainbow661314/p/3401324.html
Copyright © 2011-2022 走看看