美文网首页
在CSS中使用JS变量

在CSS中使用JS变量

作者: 3e2235c61b99 | 来源:发表于2021-10-09 17:53 被阅读0次

    下文中代码为vue代码
    在css中可以使用在CSS中定义的变量来设置样式,例如:

    <template>
      <div>
        <div class="test">css中使用js变量</div>
      </div>
    </template>
    
    <style scoped>
    .test {
      --color: pink;
      width: 200px;
      background-color: var(--color);
    
    }
    </style>
    

    效果图如下:


    使用CSS变量

    上面的变量是在CSS中定义的,不能随着一些条件的变化而变化。如果需要根据条件动态计算元素的样式,可以通过vue的计算属性与动态style结合,给元素动态注入一个样式属性,使得在CSS中可以使用注入的这个样式属性。如下:

    <template>
      <div>
        <div class="test" :style="compStyle">css中使用js变量</div>
      </div>
    </template>
    
    <script>
    export default {
      computed: {
        compStyle() {
          return {
            '--height': this.height + 'px'
          }
        }
      },
    
      data() {
        return {
          height: '100'
        }
      },
    }
    </script>
    
    <style scoped>
    .test {
      --color: pink;
      width: 200px;
      background-color: var(--color);
      height: var(--height);
    }
    </style>
    

    效果图为:


    使用JS变量

    相关文章

      网友评论

          本文标题:在CSS中使用JS变量

          本文链接:https://www.haomeiwen.com/subject/ognqoltx.html