背景
互联网行业从业者,很多人喜爱在深夜工作,为此很多网站也做了夜间浏览模式,上面提供几种实现形式。
摸索
- 应用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>
<p>hello world</p>
- 应用JS判断,依据零碎主动切换类名管制款式
<style>
body {
--text-color: #222;
--bkg-color: #fff;
--anchor-color: #0033cc;
}
body.dark-theme {
--text-color: #eee;
--bkg-color: #121212;
--anchor-color: #809fff;
}
body {
color: var(--text-color);
background: var(--bkg-color);
}
body a {
color: var(--anchor-color);
}
</style>
<script>
if (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
) {
document.body.classList.add('dark-theme');
} else {
document.body.classList.remove('dark-theme');
}
</script>
<p>hello world</p>
- 应用按钮,通过手动点击切换css文件
<head>
<link href="light-theme.css" rel="stylesheet" id="theme_link" />
</head>
<body>
<button id="btn">切换</button>
<script>
const btn = document.querySelector('#btn');
const themeLink = document.querySelector('#theme_link');
btn.addEventListener('click', function () {
if (themeLink.getAttribute('href') == 'light-theme.css') {
themeLink.href = 'dark-theme.css';
} else {
themeLink.href = 'light-theme.css';
}
});
</script>
</body>
应用CSS filter实现
<style>
html {
background: #fff;
filter: invert(1) hue-rotate(180deg);
}
</style>
<p>hello world</p>
留神:html上必须要设置背景色,不然filter是有效的
filter其实是滤镜,invert()作用是反转色彩通道数值,接管的值在 0~1;hue-rotate() 的作用是转动色盘,接管的值在 0deg~360deg。这两个函数的具体计算形式能够参考MDN CSS filter。
filter尽管可能实现光明模式,然而有个问题,图片和背景图也会被滤镜,能够通过对图片再filter一次解决这个问题。
<style>
html {
background: #fff;
filter: invert(1) hue-rotate(180deg);
}
html img {
filter: invert(1) hue-rotate(180deg);
}
.box {
width: 100px;
height: 100px;
background-image: url('https://cdn.86886.wang/pic/20220301200132.png');
background-repeat: no-repeat;
background-size: 100px 100px;
filter: invert(1) hue-rotate(180deg);
}
</style>
<img
src="https://cdn.86886.wang/pic/20220301200132.png"
width="100px"
height="100px"
alt=""
/>
<p>hello world</p>
<div class="box"></div>
原图放弃不变,只对其余元素滤镜,效果图:
结语
尽管用filter和切换款式这两种形式都能达到目标,如果对产品要求比拟高,还是举荐应用款式切换这种形式,毕竟这种形式所有都比拟可控。filter算法会呈现某些色彩不是你心愿的滤镜成果,而本人又不好调整,应为算法比较复杂。
如何实现网站光明模式首发于聚享小站,如果对您有帮忙,不要遗记点赞反对一下呦🎉
发表回复