Acceder a una propiedad personalizada de CSS (también conocida como variable CSS) a través de JavaScript
¿Cómo se obtienen y establecen propiedades personalizadas de CSS (a las que se accede convar(…)
en la hoja de estilo) usando JavaScript (simple o jQuery)?
Aquí está mi intento fallido: hacer clic en los botones cambia lo habitualfont-weight
propiedad, pero no la costumbre--mycolor
propiedad:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style>
body {
--mycolor: yellow;
background-color: var(--mycolor);
}
</style>
</head>
<body>
<p>Let's try to make this text bold and the background red.</p>
<button onclick="plain_js()">Plain JS</button>
<button onclick="jQuery_()">jQuery</button>
<script>
function plain_js() {
document.body.style['font-weight'] = 'bold';
document.body.style['--mycolor'] = 'red';
};
function jQuery_() {
$('body').css('font-weight', 'bold');
$('body').css('--mycolor', 'red');
}
</script>
</body>
</html>