美文网首页
js获取css样式的方法-window.getComputedS

js获取css样式的方法-window.getComputedS

作者: DSuperLu | 来源:发表于2020-03-02 18:06 被阅读0次

获取元素最终在浏览器中的渲染的样式

1、用法:

window.getComputedStyle(element, [pseudo])
// 等价于
document.defaultView.getComputed(element, [pseudo])

传入的两个参数,元素和伪类,第二个参数伪类是非必传的,当不需要查询伪类时,可以忽略,或者传入null
关于上面两种用法选择哪一个,参考MDN的说法是在Firefox3.6上访问子框架内(iframe)的样式时,必须使用document.defaultView访问,其他时候可以直接使用window访问。
示例:

let box = document.getElementById('box')
let boxStyle = window.getComputedStyle(box)

2、返回值

返回值是一个实时的CSSStyleDeclaration对象,当元素的样式更改时,他会自动更新
取值的时候,需要注意css的键名是驼峰式写法。
示例:

let box = document.getElementById('box')
let boxWidth = window.getComputedStyle(box).width
let boxBC = window.getComputedStyle(box).backgroundColor

3、和HTMLElement.style的区别

HTMLElement.style获取的是内联样式,即写在元素style上的属性
示例:

<div id="box" style="height: 20px"></div>
<style>
#box {
    width: 30px;
}
</style>
<script>
    let box = document.getElementById('box')
    console.log(box.style.height) // "20px"
    console.log(box.style.width) // ""
</script>

1、你用style去获取样式的时候,如果你在style标签里或者js里加入或修改了box的样式,这部分样式是获取不到的
2、Window.getComputedStyle()是只读属性,只能用于检测样式,而HTMLElement.style可以应用于在特定元素上设置样式。

我们可以通过Window.getComputedStyle()去获取样式,使用HTMLElement.style去修改样式。

相关文章

网友评论

      本文标题:js获取css样式的方法-window.getComputedS

      本文链接:https://www.haomeiwen.com/subject/ijcbkhtx.html