简短版:在我的应用程序的 data()
中,我定义了某些颜色。基于 switch
语句,我希望 html
元素的背景为其中一种颜色。
长版:
在 data()
中,我有以下代码:
data() {
return {
item: {},
color1: '',
color2: '',
};
},
在我的 created()
函数中,我从后端获取元素。此外,我还编写了以下代码来评估 html
部分的颜色:
switch (this.item.itemType) {
case 'car': this.color1 = '#39ac39'; this.color2 = '#00ff00'; break;
case 'bus': this.color1 = '#3333ff'; this.color2 = '#1a75ff'; break;
case 'plane': this.color1 = '#ff66cc'; this.color2 = '#ffb3e6'; break;
default: this.color1 = '#'; this.color2 = '#';
}
在我的 style
部分,我想为我的整个应用程序(html
-tag)设置背景样式,样式如下:
<style>
html {
background-color: linear-gradient(to bottom, color1, color2);
}
</style>
这在 Vue 中可行吗?
最佳答案
不可能将脚本中的数据绑定(bind)到样式标签或任何样式表文件中的 CSS 规则,处理此问题的最佳方法是在主 CSS 样式文件中定义一些 CSS 变量并使用脚本更改它:
:root {
--color1:#000;
--color2:#fff;
}
html {
background-color: linear-gradient(to bottom,var(--color1), var(--color2));
}
脚本:
switch (this.item.itemType) {
case 'car': this.color1 = '#39ac39'; this.color2 = '#00ff00'; break;
case 'bus': this.color1 = '#3333ff'; this.color2 = '#1a75ff'; break;
case 'plane': this.color1 = '#ff66cc'; this.color2 = '#ffb3e6'; break;
default: this.color1 = '#'; this.color2 = '#';
}
document.documentElement.style.setProperty("--color1", this.color1)
document.documentElement.style.setProperty("--color2", this.color2)
关于javascript - Vue - 是否可以动态设置 html 元素的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61228806/