gpt4 book ai didi

javascript - 如何在初始页面加载之前加载 CSS 数据主题以防止主题之间闪烁?

转载 作者:行者123 更新时间:2023-12-05 07:10:56 24 4
gpt4 key购买 nike

我有一个数据主题,其中包含对原始 CSS 主题的大量修改。我已经有一个切换开关在工作,我将它保存到 localStorage 以便记住它。但是,每当我在已启用深色主题的页面之间切换时,它会首先加载原始主题,但在整个页面加载后 应用深色主题。我希望页面之间的这种过渡是无缝的。

我正在为 Web 应用程序使用 Node.js 和 express。

我的数据主题修改大约有 200 行。这是数据主题的一小段:

[data-theme="dark"] html {
background-color: #111111 !important;
transition: 0.3s;
}

[data-theme="dark"] .bg-light {
background-color: #333 !important;
transition: 0.3s;
}

[data-theme="dark"] .bg-white {
background-color: #000 !important;
transition: 0.3s;
}

[data-theme="dark"] .bg-black {
background-color: #eee !important;
transition: 0.3s;
}

[data-theme="dark"] .topbar {
background-color: #2196f3 !important;
color: #2a1e37 !important;
transition: 0.3s;
}

[data-theme="dark"] .btn {
background-color: #2196f3 !important;
border: 1px solid #2196f3 !important;
color: #2a1e37 !important;
transition: 0.3s;
}

等它适用于我的大部分元素。

我的问题示例显示在这个简短的 gif 中:

https://gyazo.com/d53e12b7b5ea5215659a59a67639ba37

目前,我有一个脚本可以确定是在标签中应用深色主题还是浅色主题。

function initTheme() {
console.log("initTheme() invoked!");
var darkThemeSelected =
localStorage.getItem("darkSwitch") !== null &&
localStorage.getItem("darkSwitch") === "dark";

darkThemeSelected
? document.body.setAttribute("data-theme", "dark")
: document.body.removeAttribute("data-theme");

if (darkThemeSelected){
document.getElementById("darkModeText").innerHTML=`Turn Lights On`;
document.getElementById("darkModeIcon").className="zmdi zmdi-brightness-5";
}
else {
document.getElementById("darkModeText").innerHTML=`Turn Lights Off`;
document.getElementById("darkModeIcon").className="zmdi zmdi-brightness-3";
}
}

正如您所见,我正在修改一些尚不存在的元素,因为它们存在于正文中。如何在加载之前实现深色主题?我正在使用 node.js 和 express。

最佳答案

您可以在初始化页面时禁用转换

var element = document.getElementById('body');

function toggleTransition() {
element.classList.toggle('dark');
}

function toggleNoTransition() {
element.classList.add('disabled-transition');
element.classList.toggle('dark');
setTimeout(function() {
element.classList.remove('disabled-transition');
}, 300)
}
.body {
background: white;
width: 100%;
height: 100px;
padding: 20px;
transition: 0.3s;
}
.btn {
background-color: black;
border: 1px solid black;
color: white;
transition: 0.3s;
}

.dark.body {
background: black;
transition: 0.3s;
}

.dark .btn {
background-color: #2196f3 !important;
border: 1px solid #2196f3 !important;
color: #2a1e37 !important;
transition: 0.3s;
}

.disabled-transition,
.disabled-transition * {
transition: none !important;
}
<div id="body" class="body">
<button onClick="toggleTransition()" class="btn">toggle tranisition</button>
<button onClick="toggleNoTransition()" class="btn">toggle no-tranisition</button>
</div>

关于javascript - 如何在初始页面加载之前加载 CSS 数据主题以防止主题之间闪烁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61034861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com