<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
<title>设置主题色</title>
<meta name="description" content="主题色">
<style>
:root {
background: skyblue;
color: #fff;
--pds-color: red;
}
.test-p {
color: var(--pds-color)
}
p:nth-child(3) {
color: var(--pds-color)
}
</style>
</head>
<body>
<h1 style="color:var(--pds-color)">这是标题</h1>
<p>第一个段落。</p>
<p>第二个段落。</p>
<p>第三个段落。</p>
<p class="test-p">第四个段落。</p>
<p>第五个段落。</p>
<button onclick="test('1')">深色主题</button>
<button onclick="test('2')">浅色主题</button>
</body>
<script>
function test(theme) {
theme = theme ? theme : localStorage.getItem("theme")
if (theme == "1") {
document.documentElement.style.setProperty("background", "#000")
document.documentElement.style.setProperty("color", "#fff")
document.documentElement.style.setProperty("--pds-color", "blue")
} else {
document.documentElement.style.setProperty("background", "skyblue")
document.documentElement.style.setProperty("color", "#000")
document.documentElement.style.setProperty("--pds-color", "red")
}
localStorage.setItem("theme", theme)
}
test()
</script>
</html>
H5改变主题色
最新推荐文章于 2025-06-12 20:38:06 发布
这个博客展示了如何使用HTML、CSS和JavaScript实现网页动态主题切换功能。通过点击按钮,用户可以在深色和浅色主题之间自由切换,所有元素的颜色会根据预设的CSS变量即时更新。此外,主题选择会被保存在本地存储中,以便下次访问时保持用户的偏好。
1119

被折叠的 条评论
为什么被折叠?



