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算法会出现某些颜色不是你希望的滤镜效果,不容易调节