var() 函数用于插入 CSS 变量的值。
var() 函数的语法:
var(name, value)
name:必需。变量名(必须以两个破折号(—)开头,且区分大小写)。
value:可选。回退值(在未找到变量时使用)。
示例代码片段:
/* 定义变量 */
body{
--fontSize: 18px;
--color: #000000;
}
/* 使用变量 */
div-name{
font-size : var(--fontSize);
color: var(--color);
}
<template>
<div style="display: flex; justify-content: center;">
<span v-for="item in list" :style="{'--text': item.text, '--color': item.color}"></span>
</div>
</template>
<script>
export default {
name: '',
components: {},
props: {},
data() {
return {
list: [
{ text: '"中"', color: 'red' },
{ text: '"华"', color: 'orange' },
{ text: '"人"', color: 'yellow' },
{ text: '"民"', color: 'orange' },
{ text: '"共"', color: 'green' },
{ text: '"和"', color: 'cyan' },
{ text: '"国"', color: 'blue' }
]
};
}
};
</script>
<style lang="scss" scoped>
span::after {
content: var(--text);
background-color: var(--color);
}
</style>
<template>
<view style="display: flex; justify-content: center;">
<view v-for="(item, index) in list" :style="{'--text': item.text, '--color': item.color}" :key="index"
class="text-item">
</view>
</view>
</template>
<script setup>
const list = [{
text: '"中"',
color: 'red'
},
{
text: '"华"',
color: 'orange'
},
{
text: '"人"',
color: 'yellow'
},
{
text: '"民"',
color: 'orange'
},
{
text: '"共"',
color: 'green'
},
{
text: '"和"',
color: 'cyan'
},
{
text: '"国"',
color: 'blue'
}
]
</script>
<style lang="scss" scoped>
.text-item::after {
font-size: 60px;
content: var(--text);
background-color: var(--color);
}
</style>