我在Tauri web應(yīng)用程序的黑暗模式下切換標(biāo)簽時,隨機(jī)遇到了閃爍問題。這種閃爍可能是由瀏覽器阻塞或操作系統(tǒng)處理標(biāo)簽切換引起的。我懷疑負(fù)責(zé)在黑暗和光明模式之間切換的JavaScript代碼可能導(dǎo)致了這個問題。其次,在這個奇怪的錯誤期間,側(cè)邊欄意外地關(guān)閉并再次打開。
以下是相關(guān)Javascript的概述:
const body = document.querySelector('body');
const sidebar = body.querySelector('nav');
const toggle = body.querySelector('.toggle');
const modeSwitch = body.querySelector('.toggle-switch');
const modeText = body.querySelector('.mode-text');
// Check if dark mode preference is stored in localStorage
const isDarkMode = localStorage.getItem('darkMode') === 'true';
// Check if sidebar preference is stored in localStorage
const isSidebarClosed = localStorage.getItem('sidebarClosed') === 'true';
// Set initial state based on stored preferences
if (isDarkMode) {
body.classList.add('dark');
modeText.innerText = 'Light mode';
} else {
body.classList.remove('dark');
modeText.innerText = 'Dark mode';
}
if (isSidebarClosed) {
sidebar.classList.add('close');
} else {
sidebar.classList.remove('close');
}
toggle.addEventListener('click', () => {
sidebar.classList.toggle('close');
// Store sidebar state in localStorage
const isClosed = sidebar.classList.contains('close');
localStorage.setItem('sidebarClosed', isClosed);
});
modeSwitch.addEventListener('click', () => {
body.classList.toggle('dark');
// Store dark mode state in localStorage
const isDark = body.classList.contains('dark');
localStorage.setItem('darkMode', isDark);
if (isDark) {
modeText.innerText = 'Light mode';
} else {
modeText.innerText = 'Dark mode';
}
});
// Add the 'dark' class to the body element if dark mode preference is stored
if (isDarkMode) {
body.classList.add('dark');
}
我想知道是否有辦法修改JavaScript代碼或?qū)SS進(jìn)行必要的調(diào)整,以減輕閃爍問題,并確保側(cè)邊欄保持當(dāng)前狀態(tài),而不關(guān)閉和重新打開。我想確保在黑暗模式下標(biāo)簽之間的平滑過渡。任何見解或建議將不勝感激,如果你需要任何額外的信息或進(jìn)一步澄清,請不要猶豫地問。謝謝大家!
如果menu中的Dashboard鏈接確實(shí)重新加載了頁面,那么您的問題是,在初始(重新)加載頁面時,您默認(rèn)加載的是Light主題,然后JS執(zhí)行并應(yīng)用了Dark主題...這就是你看到閃光的原因
您可以通過在初始頁面加載時加載適當(dāng)?shù)?dark主題來解決這個問題,這意味著將theme=dark保存在cookie或會話中,并根據(jù)其值從后端進(jìn)行初始加載,而不是通過JS在前端應(yīng)用它。