获取元素CSS值的一些杂碎

一、getComputedStyle

在项目中,我们经常会用到获取dom对象的css值,然后对其重新设置,一般我们都会用element.style来获取或设置,但是这种只能取到dom结构上带的style,如果是外链的那么就获取不到;那怎么办呢,我们可以用window的getCompuedStyle来获取;调用方法如下:

window.getComputedStyle(ele,null).attribute;例如获取width属性值,就window.getComputedStyle(ele,null).width;

提醒几点:1、getComputedStyle只能用window调用,而且是只读的,ele.style可读可写;

     2、方法两个参数,第一个参数是元素,第二个参数如果不是获取伪类元素的话就写null,否则就是伪类属性,例如window.getComputedStyle(ele,“:after”);

     3、getComputedStyle方法IE6~8是不支持的,不适用;

那么在低版本IE浏览器中怎么办呢,还好他有自己独特的武功秘籍,那就是currentStyle,调用方法跟ele.style类似,但功能却跟getComputedStyle相似,也是获取元素当前应用的最终CSS属性值。当然在获取属性值得时候,这两者之间调用的属性名却存在不同的地方需要注意,下面要讲到

二、getPropertyValue

  上面提到用getComputedStyle去去属性值得时候,不同浏览器属性名不同,譬如 要获取一个float属性值

window.getComputedStyle(ele,null).float这样写是不对的,应该是window.getComputedStyle(ele,null).cssFloat或window.getComputedStyle(ele,null).styleFloat,这样就要判断浏览器了。那么有没有其它方法呢,答案是肯定的,getPropertyValue就可以了,怎么用呢,window.getComputedStyle(ele,null).getPropertyValue("float")就可以了,很开心是吧,哈哈,然后这样方法只适用ie9+;IE678则是不行的,怎么办呢?那么还是继续用getAttribute。ele.getAttribute("backgroundColor")即可。

ele.getAttribute("style")在IE67下返回的是object,其它的则是string

原文地址:https://www.cnblogs.com/haohaoday/p/3449463.html