当前主题切换解决方案如下.
let themeToggler = document.getElementById('theme-toggler');
themeToggler.onclick = () => {
themeToggler.classList.toggle('fa-sun');
if (themeToggler.classList.contains('fa-sun')) {
document.body.classList.add('active');
} else {
document.body.classList.remove('active');
}
};
body.active {
--backgound: #f6f6f6;
--backgound-overlay: rgba(255, 255, 255, 0.4);
--font-colour: #202020
}
:root {
--backgound: #202020;
--backgound-overlay: rgba(32, 32, 32, 0.8);
--font-colour: #ecbf1d
}
html {
background: var(--backgound);
}
body {
box-sizing: border-box;
width: 100%;
margin: 0;
padding: 0;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet"/>
<button type="button" id="theme-toggler" class="fas fa-moon "></button>
如何实现基于时间/定时器的自动切换到黑暗模式?
1条答案
按热度按时间svujldwt1#
在解决计时器/定时问题之前,需要正确地获得html/css/JS基础。
黑暗模式应该在一个名为
.dark-mode
的类中得到体现。规则和css选择器应该得到简化,themeToggler
应该改为在两个类名.fa-sun
和.fa-moon
之间切换,以便充分利用字体-真棒类名。document.documentElement
等于HTMLHtmlElement
-元素或html
-标记。:root
在通过CSS定位HTML方面等于html
-标记。因此,css规则可以压缩为3条;两条处理与主题相关的变量声明,一条应用html主体范围内的变量。
dark-mode
的主题更改类名在HTMLHtmlElement
-元素处应用/从HTMLHtmlElement
-元素中撤回。在第二步中,可以进一步改进这种方法。只需在文档的根目录处切换
'dark-mode'
类就足够了,切换按钮的图标,以及每个图标的出现时间和方式,然后成为CSS规则集的一部分。不需要显式地切换fa
类名。CSS仍然很精简,而JavaScript则缩减为一个易于实现和注册的事件处理程序。
基于时间的切换现在可以更容易地实现,因为复杂性已经从基本的切换方法中去除。
x
的一个字符串