window.getComputedStyle()

window.getComputedStyle()

window.getComputedstyle()方法返回一个对象,该对象在应用活动样式表并解析这些值可能包含的任何基本计算后报告元素的所有CSS属性的值,即返回一个包含所有最终css属性值的对象
element.style也是获取元素css属性的,但是它只读取内联样式,即写在元素style属性上的样式;
getComputedStyle则读取最终样式,包括内联,嵌入,外联;
element.style支持读写,getComputedStyle只读;
我们可以通过使用 getComputedStyle 读取样式,通过 element.style 修改样式。
getComputedStyle 和 element.style 的相同点就是二者返回的都是 CSSStyleDeclaration 对象,取相应属性值得时候都是采用的 CSS 驼峰式写法,均需要注意 float 属性。

语法

let style = window.getComputedstyle(element, [pseudoElt]);
element

要获取计算样式的元素

let elem1 = document.getElementById("elemId");
let style = window.getComputedStyle(elem1);
pseudoElt | 可选

指定一个要匹配的伪元素的字符串,必须对普通元素省略(或null)

  let elem1 = document.getElementById("elemId");
  let style = window.getComputedStyle(elem1, '::hover')

返回值

getComputedStyle 返回的对象是 CSSStyleDeclaration 类型的对象
返回属性值。例如: valString= styleObj.getPropertyValue(‘color’)
CSS属性值可以使用getPropertyValue(propName)API或直接索引到对象,如cs [‘z-index’]或cs.zIndex。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值