乐闻世界logo
搜索文章和话题

How to detect if the os is in dark mode in browsers

2个答案

1
2

Detecting whether the operating system is in dark mode in browsers can be achieved using CSS media queries, specifically the prefers-color-scheme media feature. The prefers-color-scheme CSS media feature is used to detect the user's system color theme preference, allowing you to adjust the website or application's color scheme based on whether the system is set to dark mode or light mode.

Here's an example of how to use CSS to change the webpage style based on the operating system's dark mode setting:

css
/* When the operating system is set to dark mode, apply the following styles */ @media (prefers-color-scheme: dark) { body { background-color: #333; color: white; } } /* When the operating system is set to light mode, apply the following styles */ @media (prefers-color-scheme: light) { body { background-color: #FFF; color: black; } }

If you want to detect this preference in JavaScript, you can use the window.matchMedia method to query prefers-color-scheme. This allows you to dynamically adjust styles or perform other actions in JavaScript based on dark mode or light mode. Here's an example:

javascript
// Detect dark mode if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { // Operating system is set to dark mode // Add code adapted for dark mode here } // Use matchMedia to add a listener for changes between dark mode and light mode window.matchMedia('(prefers-color-scheme: dark)').addListener(function(e) { if (e.matches) { // System is now set to dark mode } else { // System is now set to light mode } });

Note that prefers-color-scheme is a relatively new web feature and may not be supported in some older browsers. Therefore, for compatibility considerations, you may need to implement fallback solutions or use JavaScript libraries to assist with detection.

2024年6月29日 12:07 回复

If you wish to detect whether the operating system is in dark mode from JavaScript, you can use the following code:

javascript
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { // dark mode }

To listen for changes:

javascript
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => { const newColorScheme = e.matches ? "dark" : "light"; });
2024年6月29日 12:07 回复

你的答案