• 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>
  • 相关阅读:
    java微信小程序调用支付接口
    Java开发中的23种设计模式详解(转)
    SSM框架-SpringMVC 实例文件上传下载
    设计模式--观察者模式
    设计模式之策略模式
    网络通讯简单了解
    android 五子棋开发
    android studio里的build.gradle基本属性
    android studio 真机调试
    java线程知识点
  • 原文地址:https://www.cnblogs.com/fsg6/p/13599276.html
Copyright © 2020-2023  润新知