1、上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
/* 默认的CSS变量集合 */
:root {
--primary: #2196f3;
--background: #ffffff;
--text-color: #333;
}
/* 修改主题的类 */
.dark {
--primary: #1976d2;
--background: #121212;
--text-color: #f1f1f1;
}
body {
background-color: var(--background);
}
/* 使用默认样式 */
p {
color: var(--primary);
}
h1 {
color: var(--text-color);
}
h1:hover {
cursor: pointer;
color: var(--primary);
}
/* 给按钮添加样式 */
button {
background-color: var(--primary);
color: #ffffff;
padding: 8px 16px;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
transition: all 0.3s ease-in-out;
}
</style>
<title>Dynamic Theme Demo</title>
</head>
<body>
<h1>Hello World</h1>
<p>This is a demo of switching themes with CSS variables</p>
<button onclick="toggleTheme()">切换为黑夜</button>
<script>
function toggleTheme() {
document.documentElement.classList.toggle("dark");
var button = document.querySelector("button");
var theme = document.documentElement.classList.contains("dark")
? "切换为白天"
: "切换为黑夜";
console.log(theme);
button.textContent = theme;
}
</script>
</body>
</html>
2、兼容性