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>
  • 相关阅读:
    wss的webpart的3种开发方式(转载)
    C# 2.0学习之集合2
    对C#中的TreeView添加背景图转载
    ASP.NET 2.0: 页面中链入的CSS、js文件带中文时需注意
    C# 2.0学习之泛型
    C# 2.0学习之数组
    连接 ACCESS 2007
    C# 2.0学习之事件2
    一个P2P+搜索音乐网站的策划书(转载)
    关于MOSS的应用和开发的一些联接
  • 原文地址:https://www.cnblogs.com/fsg6/p/13599276.html
Copyright © 2011-2022 走看看