Many modern operating systems like Windows and macOS offer dark mode as an option to enhance user experience and reduce eye strain in low-light settings. As a developer, it's beneficial to be able to detect the preferred color scheme of the user's operating system to provide a seamless user experience.
For CSS, the @media (prefers-dark-interface) media query can be used to apply styles specifically for dark mode. However, when using APIs like Stripe Elements that utilize JavaScript for styling, a different approach is needed.
To determine the operating system's preferred color scheme in JavaScript, you can use the following code:
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { // dark mode detected }
This code utilizes the window.matchMedia() API to check if the user's browser supports media queries and whether the '(prefers-color-scheme: dark)' media query is matched. If the query matches, it indicates that the user has enabled dark mode on their operating system.
If you need to respond to changes in the user's color scheme preferences, you can use the addEventListener() method to listen for events on the media query. The following code adds an event listener that will trigger a callback function whenever the color scheme changes:
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => { const newColorScheme = event.matches ? "dark" : "light"; // Perform necessary actions based on the new color scheme });
By utilizing these techniques, you can effectively detect and respond to the user's preferred color scheme, ensuring a consistent and optimized user experience regardless of whether they're using light or dark mode.
以上がJavaScript でダーク モードを検出するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。