简体   繁体   English

如何检测我的网站是否启用了暗模式?

[英]How can I detect if Dark Mode is enabled on my website?

How can I detect if the user of my website is using macOS / Windows with Dark Mode enabled using JavaScript or CSS?如何检测我网站的用户是否使用 macOS/Windows 并使用 JavaScript 或 CSS 启用了暗模式? Is this possible?这可能吗?

This is now possible as WebKit has added support for the prefers-color-scheme CSS media query.由于 WebKit 添加了对prefers-color-scheme CSS 媒体查询的支持,因此现在可以实现。 You can use it like so:你可以像这样使用它:

@media (prefers-color-scheme: dark) { 
    body { background: black; }
}

Or in JavaScript:或者在 JavaScript 中:

function isDarkModeEnabled() {
    return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
}

Read more about Dark Mode Support in WebKit .阅读有关WebKit 中暗模式支持的更多信息。 This is available as of Safari 12.1, see Can I use... for the latest info on browser support.这从 Safari 12.1 开始可用,有关浏览器支持的最新信息,请参阅我可以使用...。

If you want to detect if a user prefers dark mode via JavaScript you can use matchMedia :如果您想通过 JavaScript 检测用户是否更喜欢暗模式,您可以使用matchMedia

const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

Browser support: https://caniuse.com/#feat=prefers-color-scheme浏览器支持: https : //caniuse.com/#feat=prefers-color-scheme

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的网站如何检测浏览器是否使用深色/浅色主题而不是操作系统是否使用主题 - How can my website detect if a browser is using a dark/light theme NOT if the OS is using a theme 如何使用 JavaScript 检测暗模式? - How do I detect dark mode using JavaScript? 如何检查 Chrome 扩展程序中是否启用了暗模式 - How to check if Dark Mode is enabled in Chrome extension 如何加快网站上的暗模式延迟? - How do I speed up Dark mode delay on website? 如何保存 cookies 以进行暗模式和亮模式切换? - How can I save cookies for dark mode and light mode toggling? 如何检测到在IE11兼容模式下启用了Skype for Business点击通话? - How can I detect that Skype For Business Click to Call is enabled in IE11 compatibility mode? 如何更改 state 以使我的切换按钮更改为暗模式? - How can i change the state for my toggle button to change to dark mode? 如何在 Electron 应用程序的两个 windows 上放置主题(暗/亮模式)? - How I can put a theme (dark/light mode) on my two windows of Electron app? 当我在黑暗模式下刷新页面时,网站的常规颜色就会显示 - The regular color of my website shows up when I refresh my page in dark mode 如何在深色模式下显示浅色徽标? - How can I show light logo in dark mode?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM