使用css 中的 var() 函数实现 css调用js变量
- 在最外层的标签上加上自定义css属性
//一定要写在最外层||父级的div上
<div style='--mianColor: #f00'>
</div>
- 定义一个sass变量 全局使用,需要的地方使用这个scss变量
$mainColor: var(--mainColor);
.content {
color: $mainColor;
}
- 把
--mainColor
弄成变量 修改initTheme即可全局更改使用$mainColor的元素
<template>
<div :style='initTheme'>
</div>
<template>
<script>
export default {
data() {
return {
initTheme: {
'--mainColor': '#f00'
}
}
}
}
</script>
<!-- Use preprocessors via the lang attribute! e.g. <template lang="pug"> -->
<template>
<div id="app" :style='mainConfig'>
<button @click='changeMain'>切换主题</button><br /><br /><br />
<a>asdfasdfasd</a>
<div class='content'>背景颜色的地方</div>
</div>
</template>
<script>
export default {
data() {
return {
color: '#f00',
message: 'Welcome to Vue!',
mainConfig: {
"--mainColor" : '#f00',
"--mainBackground" : '#fa3',
}
};
},
methods: {
changeMain() {
this.mainConfig['--mainColor'] = this.getRandomColor()
this.mainConfig["--mainBackground"] = this.getRandomColor()
},
getRandomColor() {
var r = Math.floor(Math.random() * 256); // 生成0-255之间的随机整数作为红色通道值
var g = Math.floor(Math.random() * 256); // 生成0-255之间的随机整数作为绿色通道值
var b = Math.floor(Math.random() * 256); // 生成0-255之间的随机整数作为蓝色通道值
var color = "rgb(" + r + "," + g + "," + b + ")";
return color;
}
}
};
</script>
<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<style lang="scss">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
$mainColor: var(--mainColor);
$mainBackground: var(--mainBackground);
a {
color: $mainColor;
}
.content {
color: $mainColor;
background: $mainBackground;
}
</style>