Изменение переменных с помощью JavaScript
Поскольку CSS-переменные имеют доступ к DOM, JavaScript может и читать, и изменять их.
Скрипт ниже показывает один из способов отобразить и изменить --primary-bg-color. Если этот язык для вас ещё новый, узнать больше можно в нашем учебнике по JavaScript.
Пример
Чтобы прочитать переменную, скрипт вызывает getComputedStyle(), а затем getPropertyValue(). Чтобы изменить значение, скрипт вызывает style.setProperty().
Prompt
Создайте HTML-страницу, использующую CSS-переменные на элементе :root (например, --primary-bg-color). Добавьте две кнопки: одну, которая использует getComputedStyle и getPropertyValue, чтобы показать текущее значение --primary-bg-color, и другую, которая использует style.setProperty, чтобы изменить --primary-bg-color на "green". Примените переменную к цвету фона контейнера, чтобы изменение было заметно.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change CSS Variables With JavaScript</title>
<style>
:root {
--primary-bg-color: coral;
}
.container {
background-color: var(--primary-bg-color);
padding: 25px;
margin: 20px 0;
}
h1 {
color: white;
}
</style>
</head>
<body>
<h1>Change CSS Variables With JavaScript</h1>
<div class="container">
<p>This container has a background color set by the CSS variable --primary-bg-color.</p>
</div>
<button onclick="myFunction_get()">Get Variable Value</button>
<button onclick="myFunction_set()">Change Variable to Green</button>
<script>
// Get the root element
var r = document.querySelector(':root');
// Function for getting a variable value
function myFunction_get() {
// Get the styles (properties and values) for the root
var rs = getComputedStyle(r);
// Alert the value of the --primary-bg-color variable
alert("The value of --primary-bg-color is: " + rs.getPropertyValue('--primary-bg-color'));
}
// Function for setting a variable value
function myFunction_set() {
// Set the value of variable --primary-bg-color to another value (in this case "green")
r.style.setProperty('--primary-bg-color', 'green');
}
</script>
</body>
</html>