CSSOM之getComputedStyle,currentStyle,getPropertyValue,getAttribute

js关于CSSOM编程的样式相关几个常用的方法

webkit:getComputedStyle,getPropertyValue

IE:currentStyle,getAttribute

前言

jquery 中的 css() 方法,其底层运用的就是 getComputedStyle,getPropertyValue 方法。

getComputedStyle

getComputedStyle 是一个可以获取当前元素所有最终使用的css属性值的方法。返回一个CSSStyleDeclaretion 实例的对象。只读

语法如下:

var style = window.getComputedStyle("元素", "伪类");

例如:

var dom = document.getElementById("test"),
    style = window.getComputedStyle(dom , ":after");

getComputedStyle与style的区别

我们使用element.style也可以获取元素的CSS样式声明对象,但是其与getComputedStyle方法还有有一些差异的。

1.element.style 属性可读可写

2.getComputedStyle 返回的是元素最终的样式,而element.style 只是style属性的值

注意:getComputedStyle 方法在 window ,和document.defaultView 上

window.getComputedStyle===document.defaultView.getComputedStyle  返回True.

getComputedStyle与currentStyle

currentStyle是IE浏览器自娱自乐的一个属性,其与element.style可以说是近亲,至少在使用形式上类似,element.currentStyle,差别在于element.currentStyle返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,页面中嵌入的<style>属性等)。

因此,从作用上将,getComputedStyle方法与currentStyle属性走的很近,形式上则stylecurrentStyle走的近。不过,currentStyle属性貌似不支持伪类样式获取,这是与getComputedStyle方法的差异,也是jQuery css()方法无法体现的一点。

getPropertyValue

getPropertyValue方法可以获取CSS样式申明对象上的属性值(直接属性名称),例如:

window.getComputedStyle(element, null).getPropertyValue("float");

  

如果我们不使用getPropertyValue方法,直接使用键值访问,其实也是可以的。但是,比如这里的的float,如果使用键值访问,则不能直接使用getComputedStyle(element, null).float,而应该是cssFloatstyleFloat,自然需要浏览器判断了,比较折腾!

使用getPropertyValue方法不必可以驼峰书写形式(不支持驼峰写法),例如:style.getPropertyValue("border-top-left-radius");

兼容性
getPropertyValue方法IE9+以及其他现代浏览器都支持,

OK,一涉及到兼容性问题(IE6-8肿么办),感觉头开始微微作痛了~~,不急,IE自由一套自己的套路,就是getAttribute方法

getPropertyValue和getAttribute

在老的IE浏览器(包括最新的),getAttribute方法提供了与getPropertyValue方法类似的功能,可以访问CSS样式对象的属性。用法与getPropertyValue类似:

style.getAttribute("float");

 

综上,获取元素的兼容性样式:

var oButton = document.getElementById("button");

if (oButton) {
    oButton.onclick = function() {
        var oStyle = this.currentStyle? this.currentStyle : window.getComputedStyle(this, null);
        if (oStyle.getPropertyValue) {
            alert("getPropertyValue下背景色:" + oStyle.getPropertyValue("background-color"));
        } else {
            alert("getAttribute下背景色:" + oStyle.getAttribute("backgroundColor"));
        }
    };
}

 

posted @ 2016-12-11 15:29  btg.yoyo  阅读(296)  评论(0编辑  收藏  举报