检测系统是否开启dark mode,自动切换夜间模式。并提供一个按钮可供来回切换light mode和dark mode
但是现在遇到问题,
在系统为light mode时,网页点击按钮切回dark mode,这时切换到其他程序,再返回浏览器网页界面时,原本浏览器应该显示dark mode变回light mode。
同样,在系统为dark mode 时,网页点击按钮切回light mode,这时切换到其他程序,再返回浏览器网页界面时,原本浏览器应该显示light mode变回dark mode。
不知道遇到什么问题
相关代码
var t = Cookies.get("theme");
const isDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches
const isLightMode = window.matchMedia("(prefers-color-scheme: light)").matches
const isNotSpecified = window.matchMedia("(prefers-color-scheme: no-preference)").matches
const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
if (isLightMode) t!=='dark' ? activateLightMode() : activateDarkMode()
else if (isDarkMode) t !== 'light' ? activateDarkMode(): activateLightMode()
else if (isNotSpecified || hasNoSupport){
console.log('You specified no preference for a color scheme or your browser does not support it. I Schedule dark mode during night time.')
now = new Date();
hour = now.getHours();
isNight = (hour < 6 || hour >= 18)
if (isNight) t !== 'light' ? activateDarkMode(): activateLightMode()
else t!=='dark' ? activateLightMode() : activateDarkMode()
}
function activateDarkMode(){
document.documentElement.setAttribute('data-theme', 'dark')
Cookies.set('theme','dark', { expires: 2 })
}
function activateLightMode(){
document.documentElement.removeAttribute('data-theme', 'dark')
Cookies.set('theme','light', { expires: 2 })
}
$(function () {
var is_Snackbar = GLOBAL_CONFIG.Snackbar !== undefined ? true : false
window.matchMedia("(prefers-color-scheme: dark)").addListener(function (e) {
if (e.matches) {
activateDarkMode()
change_light_icon()
} else {
activateLightMode()
change_dark_icon()
}
})
if (Cookies.get("theme") == "dark") {
change_light_icon()
} else {
change_dark_icon()
}
function change_light_icon() {
$("#nightshift").removeClass("fa-moon-o").addClass("fa-sun-o");
}
function change_dark_icon() {
$("#nightshift").removeClass("fa-sun-o").addClass("fa-moon-o");
}
function switchReadMode() {
var nowMode = document.documentElement.hasAttribute('data-theme') ? 'dark' : 'light'
if ( nowMode == 'light') {
change_light_icon()
activateDarkMode()
if (is_Snackbar) snackbarShow(GLOBAL_CONFIG.Snackbar.day_to_night)
}else{
change_dark_icon()
activateLightMode()
if (is_Snackbar) snackbarShow(GLOBAL_CONFIG.Snackbar.night_to_day)
}
}
$("#nightshift").click(function () {
switchReadMode();
});
});
假设用户手动切换了模式,下次进入页面应该按照用户的设置来,上面的代码明显没有这个步骤。
用户切换应用会不会导致了页面自动刷新,从而重新执行了模式的判断步骤。
逻辑可以修改为: