hexo-theme-keep/source/js/dark-light-toggle.js

57 lines
1.7 KiB
JavaScript
Raw Normal View History

/* global KEEP */
KEEP.initModeToggle = () => {
2020-11-20 12:02:22 +08:00
KEEP.utils.modeToggle = {
modeToggleButton_dom: document.querySelector('.tool-dark-light-toggle'),
iconDom: document.querySelector('.tool-dark-light-toggle i'),
enableLightMode() {
document.body.classList.remove('dark-mode')
document.body.classList.add('light-mode')
this.iconDom.className = 'fas fa-moon'
KEEP.styleStatus.isDark = false
KEEP.setStyleStatus()
},
enableDarkMode() {
document.body.classList.add('dark-mode')
document.body.classList.remove('light-mode')
this.iconDom.className = 'fas fa-sun'
KEEP.styleStatus.isDark = true
KEEP.setStyleStatus()
},
isDarkPrefersColorScheme() {
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)')
},
initModeStatus() {
const styleStatus = KEEP.getStyleStatus()
if (styleStatus) {
styleStatus.isDark ? this.enableDarkMode() : this.enableLightMode()
} else {
this.isDarkPrefersColorScheme().matches ? this.enableDarkMode() : this.enableLightMode()
}
},
initModeToggleButton() {
this.modeToggleButton_dom.addEventListener('click', () => {
const isDark = document.body.classList.contains('dark-mode')
isDark ? this.enableLightMode() : this.enableDarkMode()
})
},
initModeAutoTrigger() {
const isDarkMode = this.isDarkPrefersColorScheme()
isDarkMode.addEventListener('change', (e) => {
e.matches ? this.enableDarkMode() : this.enableLightMode()
})
}
}
KEEP.utils.modeToggle.initModeStatus()
KEEP.utils.modeToggle.initModeToggleButton()
KEEP.utils.modeToggle.initModeAutoTrigger()
}