在CSS中使用JS变量

2021-10-09  本文已影响0人  3e2235c61b99

下文中代码为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变量
上一篇下一篇

猜你喜欢

热点阅读