getComputedStyle获取元素样式值

html:

    <style>
      .div {
        width: 200px;
        height: 200px;
        background-color: greenyellow;
      }
    </style>
  </head>
  <body>
    <div class="div">一些文字</div>
    <script>
      const div = document.getElementsByClassName('div')[0]
      const style = getComputedStyle(div)
      console.log(style)
      console.log(style.backgroundColor) // rgb(173, 255, 47)
    </script>
  </body>

vue:

  mounted() {
    const ref = this.$refs.h1Ref
    const style = getComputedStyle(ref)
    console.log(style)
    console.log(style.color)
    ref.classList.add('aa')
  }

 

注意:

  1、当div有padding值时,

    getComputedStyle获取的height会比offsetHeight小,小的那部分就是padding的值

    如果设置了box-sizing: border-box;  那此时getComputedStyle和offsetHeight的值一样

  2、offsetHight是数字,不带单位;getComputedStyle获取到的height是字符串,带单位

  3、getComputedStyle只能获取,ref可以获取也可以设置

  4、扩展:wrapper中有上下两个盒子,下面的盒子的高度需要依赖上面的盒子高度计算而来,一般有两种解决方式。一是通过设置第二个盒子动态高度,二是设置flex: 1

posted @ 2021-09-24 21:45  吴小明-  阅读(440)  评论(0编辑  收藏  举报