[閒聊] 這個toggleMode切換dark mode

作者: firesnake (傷心碧)   2024-01-17 14:08:56
這個toggle mode 切換dark mode/light mode
不知道哪裡出了問題
code是bard生成的
css:
body {
/* Light mode styles */
background-color: white;
color: black;
}
body.dark-theme {
/* Dark mode styles */
background-color: black;
color: white;
textarea {
background-color: black;
color: white; /* Optional: Set text color to white for better
readability */
border-style: dashed; /* Example: Set a dashed border */
}
a {
color: #6C9AB0; /* You can use any valid color value */
}
}
javascript:
const toggleThemeButton = document.getElementById("toggle-theme");
const body = document.body;
let currentTheme = null;
function toggleTheme() {
if (currentTheme === "dark") {
body.classList.remove("dark-theme");
body.style.color = ""; // Reset text color to default
localStorage.setItem("theme", "light");
currentTheme = "light";
toggleThemeButton.textContent = "Dark Mode";
} else {
body.classList.add("dark-theme");
body.style.color = "#fff"; // Set text color for dark theme
localStorage.setItem("theme", "dark");
currentTheme = "dark";
toggleThemeButton.textContent = "Light Mode";
}
// Force a reflow
body.offsetHeight;
}
toggleThemeButton.addEventListener("click", toggleTheme);
// Check for saved theme preference
const savedTheme = localStorage.getItem("theme");
if (savedTheme === "dark") {
toggleTheme(); // Apply dark mode if saved preference is dark
}
html:
<button id='toggle-theme'>Dark Mode</button>
實際狀況:用edge 和chrome 可以正確切換背景色和textarea 背景色和<a href>
tag的顏色 但是文字部分的顏色一定要F5 or 重整頁面後
才會變色 不知道該怎麼修正
用Safari的話倒是可以正確切換所有文字顏色,除了textarea背景顏色又沒有正確切換
實裝網頁
https://cloudliter.com/start.php

Links booklink

Contact Us: admin [ a t ] ucptt.com