Background:CSS_variables,var()
Las variables CSS son similares a las variables que definimos en SCSS y LESS. La diferencia es que CSS ite la inserción de los valores de la variable CSS a través de JS. El nombre de la variable representado por un identificador que comienza con dos guiones --(por ejemplo --main-color: #b4a078), luego use la función var(--main-color) para hacer referencia a ella.La función var() acepta dos argumentos (por ejemplo var(--main-color, gray),), el primer argumento es el nombre de la propiedad personalizada a sustituir, el segundo argumento opcional a la función sirve como valor de reserva).
El siguiente ejemplo presenta cómo ajustar el estilo de los elementos o incluso los pseudo elementos por JS
<style>
/* global custom-variables */
/* :root {
--r: 51;
--g: 51;
--b: 51;
} */
main {
width: 100%;
padding: 60px 29px;
display: flex;
flex-direction: column;
align-items: center;
}
label {
display: flex;
align-items: center;
}
input {
padding: 0;
width: 29px;
height: 29px;
}
div.variables-block {
width: 100%;
display: flex;
justify-content: center;
margin-top: 29px;
}
/* 局部 custom-variables */
div.variables-block > div {
--r: 51;
--g: 51;
--b: 51;
}
div.variables-block > div::after {
content: "";
display: inline-block;
width: 52px;
height: 52px;
background: rgb(var(--r), var(--g), var(--b));
}
</style>
<main>
<label for="color">
Por favor seleccione un color de tema:
<input
type="color"
v-model="value"
id="color"
/>
</label>
<div class="variables-block">
<div
v-for="(ele, idx) in colorList"
:ref="'variable' + idx">
</div>
</div>
</main>
<script>
const Color = require('https://tutorialesenlinea.descargarjuegos.org/CSS3/color.js');
const INITIAL_COLOR = '#b4a078';
export default {
data() {
return {
value: INITIAL_COLOR,
}
},
computed: {
colorList() {
const mainColor = this.value.length === 7 && this.value || INITIAL_COLOR;
return this.getColorList(mainColor);
}
},
methods: {
getColorList(val) {
const color = Color(val);
return Array.from({length: 10}).map((v, i) => {
let rgb = color.mix(Color('white'), i / 10);
this.$nextTick(() => {
const style = this.$refs[`variable${i}`][0].style;
style.setProperty('--r', rgb.red());
style.setProperty('--g', rgb.green());
style.setProperty('--b', rgb.blue());
})
});
}
}
}
</script>
Ver resultado