javascript - 集成暗模式的系统级设置
问题描述
我需要您的帮助才能集成prefers-color-scheme
到我现有的暗模式设置中。
这是我正在使用的 JS:
<script>
const switcher = document.querySelector('#switcher');
const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');
function setTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
const src = 'https://example.com/' + (theme === 'light' ? 'DARK-MODE-1.png' : 'LIGHT-MODE-1.png');
switcher.setAttribute('src', src);
}
const theme = localStorage.getItem('theme') || 'light';
setTheme(theme);
toggleSwitch.addEventListener('change', (e) => {
const theme = e.currentTarget.checked ? 'dark' : 'light';
setTheme(theme);
});
</script>
这是 src="" 从上面的 JS 获取并生成图像路径的 HTML(例如 example.com/DARK-MODE-1.png)。
<label class="theme-switch" for="checkbox">
<span title="Click to enable/disable Dark Mode">
<img id="switcher" src="">
</span>
<input type="checkbox" id="checkbox"/>
</label>
现在我想使用prefers-color-scheme
这段代码,所以当用户的系统处于暗模式时,它会自动切换到暗模式。如果用户机器处于光照模式,则应提供光照模式。此外,用户应该能够根据需要切换到任何模式。
感谢您的帮助和您的时间!
解决方案
“可以在 Javascript 中检测深色模式,方法是使用 window.matchMedia() 检查是否匹配 prefers-color-scheme:深色 CSS 媒体查询。”
let matched = window.matchMedia('(prefers-color-scheme: dark)').matches;
if(matched)
const theme = 'dark'; //switch to dark theme
else
const theme = 'light'; //use light theme
window.matchMedia('(prefers-color-scheme: )')
接受dark
,light
和no-preference
尽可能的查询。
(通过有用的角度.com)
我希望我的回答能帮助你更接近你想要的结果。
推荐阅读
- vue.js - fusioncharts在重新加载时出现渲染错误
- c++ - 隐式 const/nonconst 运算符 bool
- hpc - qsub -t 工作“已死”
- flutter - MissingPluginException(在通道 plugins.flutter.io/image_picker 上找不到方法 pickImage 的实现)
- docker - 在 Jenkinsfile 中标记 docker 图像
- microsoft-graph-api - Azure:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:找不到有效的证书路径 toRequestedTarget
- sql - MSCRM 2013 - 内部部署 - 导入组织错误
- java - MySql 中的 CURRENT_TIMESTAMP 正在更新格式不正确的表
- unity3d - Unity 3D Camera在添加空动画后不会水平转动
- laravel - 如何从博客文章中获取用户名?