css 变量优先使用最近的,js 可以动态修改变量值
<!DOCTYPE html>
<html lang="en" style="background-color: #f8f8f8;">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<style>
body {
--background-color: green;
--color: white;
}
h1 {
background-color: var(--background-color);
}
p {
--background-color: gray;
--color: white;
background-color: var(--background-color);
}
p span {
color: var(--color);
}
</style>
</head>
<body>
<h1>2秒后我的背景有变化</h1>
<p>
<b>123456</b>
<span>这里会调用最近的变量</span>
</p>
</body>
<script>
setTimeout(() => {
document.body.style.setProperty('--background-color', '#00f');
}, 2000)
</script>
</html>