实现网站黑暗模式
1.CSS媒体查询,根据系统自动切换不同样式
//还可以配合css变量
<style>
@media (prefers-color-scheme: dark) {
body {
color: #eee;
background: #121212;
}
body a {
color: #809fff;
}
}
@media (prefers-color-scheme: light) {
body {
color: #222;
background: #fff;
}
body a {
color: #0033cc;
}
}
</style>
2.使用JS判断,根据系统自动切换类名控制样式
<style>
body {
background:#fff
}
body.dark-theme {
background:#000
}
</style>
<script>
if (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
) {
document.body.classList.add('dark');
} else {
document.body.classList.remove('dark');
}
</script>
通过事件触发,切换样式
<head>
<link href="light.css" id="theme" />
</head>
<body>
<button id="btn">切换</button>
<script>
const btn = document.querySelector('#btn');
const themeLink = document.querySelector('#theme');
btn.addEventListener('click', function () {
if (themeLink.getAttribute('href') == 'light-theme.css') {
themeLink.href = 'dark.css';
} else {
themeLink.href = 'light.css';
}
});
</script>
</body>
3.使用CSS filter
<style>
html {
background: #fff;
filter: invert(1) hue-rotate(180deg);
}
</style>
注意:html上必须要设置背景色,不然filter是无效的
filter其实是滤镜,invert()作用是反转颜色通道数值,接收的值在 01;hue-rotate() 的作用是转动色盘,接收的值在 0deg360deg。
https://developer.mozilla.org/en-US/docs/Web/CSS/filter
filter虽然能够实现黑暗模式,但图片和背景图也会被滤镜,可以通过对图片再filter一次解决这个问题。
html img {
filter: invert(1) hue-rotate(180deg);
}
如果对产品要求高,可以使用样式切换的方式,因为filter算法会出现某些颜色不是你希望的滤镜效果,不容易调节
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探