<!DOCTYPE html>
<html>
<head>
<style>
:root {
--blue: #1e90ff;
--white: #ffffff;
}
body {
background-color: var(--blue);
}
h2 {
border-bottom: 2px solid var(--blue);
}
.container {
color: var(--blue);
background-color: var(--white);
padding: 15px;
}
.container button {
background-color: var(--white);
color: var(--blue);
border: 1px solid var(--blue);
padding: 5px;
}
</style>
<script>
var r = document.querySelector(':root');
function myFunction_get() {
var rs = getComputedStyle(r);
alert("The value of --blue is: " + rs.getPropertyValue('--blue'));
}
function myFunction_set() {
r.style.setProperty('--blue', 'lightblue');
}
</script>
</head>
<body>
<h1>使用 JavaScript 获取和更改 CSS 变量</h1>
<div class="container">
<h2>Welcome to Shanghai!</h2>
<p>Shanghai is one of the four direct-administered municipalities of the People's Republic of China.</p>
<p>Shanghai is one of the four direct-administered municipalities of the People's Republic of China.</p>
<p>
<button>Yes</button>
<button>No</button>
</p>
</div>
<br>
<button type="button" onclick="myFunction_get()">使用 JavaScript 来获取 CSS 变量</button>
<button type="button" onclick="myFunction_set()">使用 JavaScript 来更改 CSS 变量</button>
</body>
</html>