下文中代碼為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中定義的笼呆,不能隨著一些條件的變化而變化。如果需要根據(jù)條件動態(tài)計算元素的樣式,可以通過vue的計算屬性與動態(tài)style結合,給元素動態(tài)注入一個樣式屬性撮奏,使得在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變量