简体   繁体   中英

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? Is this possible?

This is now possible as WebKit has added support for the prefers-color-scheme CSS media query. You can use it like so:

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

Or in JavaScript:

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

Read more about Dark Mode Support in WebKit . This is available as of Safari 12.1, see Can I use... for the latest info on browser support.

If you want to detect if a user prefers dark mode via JavaScript you can use matchMedia :

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

Browser support: https://caniuse.com/#feat=prefers-color-scheme

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM