Ist es möglich, eine in CSS verwendete Variable mit jQuery zu ändern? Ein einfaches Beispiel:
html {
--defaultColor: teal;
}
.box {
background: var(--defaultColor);
width: 100px;
height: 100px;
margin: 5px;
float: left;
}
.circle {
background: #eee;
border: 2px solid var(--defaultColor);
width: 100px;
height: 100px;
margin: 5px;
float: left;
border-radius: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickToChange" type="button" style="width: 100%;">Click to Change</button>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<br/>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
Wie kann ich die Farbe der Variablen zum Beispiel von Türkis in Rot ändern? Das funktioniert nicht.
$("#clickToChange").click(function(){
$(html).css("--defaultColor", "red");
});
Sie können die CSS-Variable mit einfachem JavaScript elem.style.setProperty("variableName", "variableProp");
ändern.
$("html").on('click', function() {
$("body").get(0).style.setProperty("--color", "hotpink");
});
body {
--color: blue;
background-color: var(--color);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
click me!
Einfachste Lösung IMHO: Ändern Sie eine Klasse, die wiederum die Standardfarbe ändert:
html {
--defaultColor: teal;
}
html.someOtherDefaultColor {
--defaultColor: rebeccapurple;
}
$("#clickToChange").click(function(){
$(html).toggleClass("someOtherDefaultColor");
});
Die fragliche Methode ist document.body.style.setProperty($property, value);
, wobei $ property die CSS-Variable ist.