菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
402
0

getComputedStyle

原创
05/13 14:22
阅读数 34387

getComputedStyle

getComputedStyleelement.style 的相同点就是二者返回的都是 CSSStyleDeclaration 对象,取相应属性值得时候都是采用的 CSS 驼峰式写法

  const demo = document.getElementById('demo')
 const styleObj = getComputedStyle(demo)
 console.log(styleObj.width)
 console.log(styleObj.backgroundColor)

 

而不同点就是:

  • element.style 读取的只是元素的内联样式,即写在元素的 style 属性上的样式;而 getComputedStyle 读取的样式是最终样式,包括了内联样式嵌入样式外部样式

  • element.style 既支持读也支持写,我们通过 element.style 即可改写元素的样式。而 getComputedStyle 仅支持读并不支持写入。我们可以通过使用 getComputedStyle 读取样式,通过 element.style 修改样式

总结:我们可以通过使用 getComputedStyle 读取样式,通过 element.style 修改样式

 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #demo {
        width: 100px;
        height: 100px;
        background-color: pink;
      }
    </style>
  </head>
  <body>
    <div id="demo" style="color: red">文字</div>
    <script>
      const demo = document.getElementById('demo')
      // 注意: 元素.style只能拿到行内样式
      console.log(demo.style.width)
      console.log(demo.style.color)

      // width,height, bgc 不是行内样式,但是需要在js中获取
      // getComputedStyle 可以拿到当前元素的所有样式
      const demoStyleObj = getComputedStyle(demo)
      console.log(demoStyleObj.width)
      console.log(demoStyleObj.height)
      console.log(demoStyleObj.backgroundColor)
      console.log(demoStyleObj.color)
    </script>
  </body>
</html>

 

发表评论

0/200
402 点赞
0 评论
收藏