通过JS可以识别设备是否是黑夜模式(dark mode)
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
// dark mode
}
可以监听黑夜模式的变化:
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
const newColorScheme = e.matches ? "dark" : "light";
});
浏览器兼容性
参考资料:
- https://stackoverflow.com/questions/50840168/how-to-detect-if-the-os-is-in-dark-mode-in-browsers
- https://developer.mozilla.org/zh-CN/docs/Web/API/Window/matchMedia
- https://developer.mozilla.org/zh-CN/docs/Web/CSS/@media/prefers-color-scheme
转载请注明出处
《在Web前端识别设备黑夜模式(dark mode)》https://www.ywlib.com/archives/172.html (from 一闻自习室)
本文固定链接
https://www.ywlib.com/archives/172.html
标签
dark mode, 黑夜模式, javascript, web