获取元素CSS值之getComputedStyle、currentStyle、style

1.getComputedStyle

通过getComputedStyle可以获取当前元素所有最终使用的CSS属性值,返回的样式是一个实时的 CSSStyleDeclaration 对象,当元素的样式更改时,它会自动更新本身。(只读!)

语法:

var style = window.getComputedStyle(element, [pseudoElt]);

element:用于获取计算样式的Element
pseudoElt 可选:指定一个要匹配的伪元素的字符串。必须对普通元素省略(或null)

示例:

var ele = document.getElementById("eleId");
var style1 = window.getComputedStyle(ele, null);
var style2 = window.getComputedStyle(ele, ":after");
var height = window.getComputedStyle(ele, null).getPropertyValue("height");
var height = window.getComputedStyle(ele, null).height;

区别于jQuery中的css()方法,getComputedStyle可以获取伪类元素样式

2.getComputedStyle与style的区别

element.style也可以获取元素的CSS样式声明对象,它们的差异体现在:

1.element.style可读可写,而getComputedStyle只读,只可以获取样式
2.element.style只能获取元素style属性中的CSS样式,而getComputedStyle获取的是应用在元素上的所以CSS属性(即使没有CSS代码)

3.getComputedStyle与currentStyle

currentStyle是IE浏览器的一个属性,在用法上与element.style相似,区别在于element.currentStyle返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,页面中嵌入的style属性等)。

因此,从作用上讲,getComputedStyle方法与currentStyle属性相似,形式上则style与currentStyle相似。不过,currentStyle属性貌似不支持伪类样式获取,这是与getComputedStyle方法的差异。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值