[英]How can I change the lite mode to dark mode according to the user's time using JS?
[英]How can I change the lite mode to dark mode according to the user's time?
如何根据用户使用JS的时间将lite模式更改为dark模式? `
// function to set a given theme/color-scheme
function setTheme(themeName) {
localStorage.setItem('theme', themeName);
document.documentElement.className = themeName;
}
// function to toggle between light and dark theme
function toggleTheme() {
if (localStorage.getItem('theme') === 'theme-dark') {
setTheme('theme-light');
} else {
setTheme('theme-dark');
}
}
// Immediately invoked function to set the theme on initial load
(function () {
if (localStorage.getItem('theme') === 'theme-dark') {
setTheme('theme-dark');
document.getElementById('dark-light-mode').checked = false;
} else {
setTheme('theme-light');
document.getElementById('dark-light-mode').checked = true;
}
})();
`
`
<label id="switch" class="switch">
<input type="checkbox" onchange="toggleTheme()" id="dark-light-mode">
<span class="slider round"></span>
</label>
`
我想通过用户的时间在明暗之间改变主题
使用可以日期object 并根据所选时间应用主题
你可以这样做。
let hour = (new Date).getHours();
if (hour >= 18) {
setTheme('theme-dark');
} else {
setTheme('theme-light');
}
如果时间大于 18,它将应用深色主题
您还需要setInterval
以便它根据条件观察时间和触发事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.