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>
  • 相关阅读:
    斐波那契数列 的两种实现方式(Java)
    单链表反转
    单链表合并
    两个有序list合并
    list去重 转载
    RemoveAll 要重写equals方法
    Java for LeetCode 138 Copy List with Random Pointer
    Java for LeetCode 137 Single Number II
    Java for LeetCode 136 Single Number
    Java for LeetCode 135 Candy
  • 原文地址:https://www.cnblogs.com/fsg6/p/13599276.html
Copyright © 2011-2022 走看看