javascript - 启用深色主题时如何防止网站闪烁为白色主题
问题描述
我的网站出现问题,当我刷新网页并启用深色主题时,它会在不到一秒的时间内闪烁为白色并变回黑暗,因此如何解决该问题
我的js代码,
/*==================== DARK LIGHT THEME ====================*/
const themeButton = document.getElementById('theme-button')
const darkTheme = 'dark-theme'
const iconTheme = 'bx-sun'
// Previously selected topic (if user selected)
const selectedTheme = localStorage.getItem('selected-theme')
const selectedIcon = localStorage.getItem('selected-icon')
// We obtain the current theme that the interface has by validating the dark-theme class
const getCurrentTheme = () => document.body.classList.contains(darkTheme) ? 'dark' : 'light'
const getCurrentIcon = () => themeButton.classList.contains(iconTheme) ? 'bx-moon' : 'bx-sun'
// We validate if the user previously chose a topic
if (selectedTheme) {
// If the validation is fulfilled, we ask what the issue was to know if we activated or deactivated the dark
document.body.classList[selectedTheme === 'dark' ? 'add' : 'remove'](darkTheme)
themeButton.classList[selectedIcon === 'bx-moon' ? 'add' : 'remove'](iconTheme)
}
// Activate / deactivate the theme manually with the button
themeButton.addEventListener('click', () => {
// Add or remove the dark / icon theme
document.body.classList.toggle(darkTheme)
themeButton.classList.toggle(iconTheme)
// We save the theme and the current icon that the user chose
localStorage.setItem('selected-theme', getCurrentTheme())
localStorage.setItem('selected-icon', getCurrentIcon())
})
/*==================== SCROLL REVEAL ANIMATION ====================*/
const sr = ScrollReveal({
origin: 'top',
distance: '30px',
duration: 1000,
reset: true
});
sr.reveal(` .home__data, .home__img,
.about__data, .about__img,
.services__content, .menu__content,
.app__data, .app__img,
.contact__data, .contact__button,
.footer__content`, {
interval: 200
})
解决方案
您的代码没有问题,Web 浏览器会首先加载您的 HTML 文件,然后加载您的 CSS 文件,然后才加载您的 JavaScript 文件。
默认情况下,HTML 网页是空白的,它们是白色的,所以在你的 JavaScript 文件被渲染到 DOM 之前,你会首先看到白色背景。
推荐阅读
- cassandra - 基于令牌范围的分区键查询的性能?
- laravel - Response.php 第 458 行中的 InvalidArgumentException:HTTP 状态代码“1”无效
- django - 在 django 的 createview 中显示外键的关联值
- ruby-on-rails - ActiveAdmin 使用自定义方法过滤数据并匹配父表列中存在的数据
- python - 如何使用 LinearSVM 训练数据集?
- android - 修改android库的方法
- c# - 如何像原生功能一样以 xamarin 形式实现滑动删除?
- javascript - 如何停止调用 window.open 覆盖函数的另一个函数
- android - 从清单中删除后,应用权限显示在应用设置中
- python - Python在不改变提示的情况下激活虚拟环境