start
- 记录一下,如何使用 js 代码控制样式。
css3 自带的 var
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
--themeColor: tomato;
}
.item {
background-color: var(--themeColor);
}
</style>
</head>
<body>
<div class="item">123</div>
</body>
</html>
Vue 中通过 JS 控制样式
<template>
<div :style="customStyle">
<div class="lazy">
我是番茄
</div>
</div>
</template>
<script>
export default {
data() {
return { customBackGround: '' }
},
somputed: {
// 自定义样式
customStyle() {
return {
'--bgColor': this.customBackGround
// '--currentThemeColor': this.$store.state.themeModule.theme.currentThemeColor.color
}
}
}
}
</script>
<style>
.lazy {
background: var(--bgColor);
border-color: var(--bgColor);
}
</style>
第三方插件 css-vars-ponyfill
在考虑各种浏览器的兼容性问题的情况下,考虑使用 第三方库:css-vars-ponyfill
;
第三方库github
地址 点击此处
在 vue 中的使用案例
<template>
<div :style="customStyle">
<div class="lazy">
我是番茄
</div>
</div>
</template>
<script>
import cssVars from 'css-vars-ponyfill'
export default {
data() {
return { customBackGround: '' }
},
created() {
cssVars({
onlyLegacy: true,
variables: {
'--bgColor': this.customBackGround
// '--currentThemeColor': this.$store.state.themeModule.theme.currentThemeColor.color
}
})
}
}
</script>
<style>
.lazy {
background: var(--bgColor);
border-color: var(--bgColor);
}
</style>