CSSのメディアクエリで判定する方法
@media (prefers-color-scheme: dark) {
body {
color: #fff;
background: #000;
}
}
JavaScriptで外観モードで判定する方法
ダークモードであればbody要素に「is-theme-dark」クラスを付与、ライトモードであれあばbody要素に「is-theme-light」クラスを付与しています。
const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const darkModeOn = darkModeMediaQuery.matches;
darkModeMediaQuery.addListener((e) => {
const darkModeOn = e.matches;
if (darkModeOn) {
document.body.classList.remove('is-light-mode');
document.body.classList.add('is-dark-mode');
} else {
document.body.classList.remove('is-dark-mode');
document.body.classList.add('is-light-mode');
}
});
ダークモードの切り替え&キャッシュへの保存方法
HTML
<button class="js-theme-switch">button</button>
JavaScript
const themeSwitch = document.querySelector(".js-theme-switch");
const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const darkModeOn = darkModeMediaQuery.matches;
themeSwitch.addEventListener('click', function(){
if(localStorage.getItem('dark-mode-settings')==='dark') {
document.body.classList.remove('is-theme-dark');
document.body.classList.add('is-theme-light');
localStorage.setItem('dark-mode-settings', 'light');
} else if (localStorage.getItem('dark-mode-settings')==='light') {
document.body.classList.remove('is-theme-light');
document.body.classList.add('is-theme-dark');
localStorage.setItem('dark-mode-settings', 'dark');
}
});
if(localStorage.getItem('dark-mode-settings')==='dark') {
document.body.classList.add('is-theme-dark');
} else if (localStorage.getItem('dark-mode-settings')==='light') {
document.body.classList.add('is-theme-light');
} else {
if (darkModeOn) {
document.body.classList.remove('is-theme-light');
document.body.classList.add('is-theme-dark');
localStorage.setItem('dark-mode-settings', 'dark');
} else {
document.body.classList.remove('is-theme-dark');
document.body.classList.add('is-theme-light');
localStorage.setItem('dark-mode-settings', 'light');
}
}