如何在页面加载时阻止浅色模式闪烁到较暗的背景 [英] How to stop light mode flickering to darker background on page load
问题描述
所以我有一些脚本可以在我的网站上在明暗模式之间切换.暗模式是默认设置.问题是,每当打开浅色模式时,加载的每个页面都会在加载浅色模式之前闪烁到深色模式一秒钟.我真的很希望不要这样做,并且非常感谢你们能提供的任何帮助.提前致谢!
So I have a bit of script for toggling between light and dark modes on my site. The dark mode is the default. Problem is, whenever the light mode is toggled on, with every page load it flickers to the dark mode for just a second before loading the light mode. I would really like it to not do this and super appreciate any help you all can give. Thanks in advance!
我的代码如下:
if (localStorage['blackout']) {
if (Number(localStorage['blackout']) == 1) {
$('BODY').addClass('blackout');
} else {
$('BODY').removeClass('blackout');
}
} else {
localStorage['blackout'] = 0;
$('BODY').removeClass('blackout');
}
$('BODY').show();
$('#boToggle').on('click', function(){
if (Number(localStorage['blackout']) == 0) {
localStorage['blackout'] = 1;
$('BODY').addClass('blackout');
} else {
localStorage['blackout'] = 0;
$('BODY').removeClass('blackout');
}
});
推荐答案
把你的 JS (从本地存储读取并应用类的部分)放在中code> 部分,并将类添加到
标记,以便在解析和显示
body
之前执行它.
Put your JS (the part reading from local storage and applying the class) in the <head>
section, and add the class to the <html>
tag, so that it get executed before the body
is parsed and displayed.
您可以通过这个简单的工作演示尝试一下:
You can try it with this simple working demo:
<html>
<head>
<script>
// Do this before the body gets parsed
if (localStorage.getItem('darkmode') === '1') {
document.documentElement.classList.add('darkmode');
}
</script>
<style>
.darkmode body { background: #222; }
.darkmode .light-only { display: none; }
html:not(.darkmode) .dark-only { display: none; }
</style>
</head>
<body>
<button id="darkToggle">
Switch to
<span class="dark-only">light</span>
<span class="light-only">dark</span>
mode
</button>
<script>
document.querySelector('#darkToggle').addEventListener('click', function() {
var wasDarkMode = localStorage.getItem('darkmode') === '1';
localStorage.setItem('darkmode', wasDarkMode ? '0' : '1');
document.documentElement.classList[wasDarkMode ? 'remove' : 'add']('darkmode');
});
</script>
</body>
</html>
这篇关于如何在页面加载时阻止浅色模式闪烁到较暗的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!