zoukankan      html  css  js  c++  java
  • getComputedStyle

    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 {
             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>
  • 相关阅读:
    mysql之drop、truncate和delete的区别
    mysql之表结构,表空间,段,区,页,MVCC(待整理)
    mysql之子查询、视图、事务及pymysql等
    mysql之单表查询、多表查询
    解决跨域问题!
    项目--2
    项目--1
    后端接口书写
    VUE-组件
    VUE基本写法
  • 原文地址:https://www.cnblogs.com/fsg6/p/13599276.html
Copyright © 2011-2022 走看看