我是 JavaScript 和 html 的初學者,我做了一個簡單的按鈕:
<button id="button6" type="button" class="btns"
onclick="LightTheme()">Light Mode</button>
. 這應該將頁面的視圖更改為淺色模式,而不是深色。腳本是:
function LightTheme() {
document.body.style.backgroundColor = "#DBE6FD";
document.getElementById('button_circle').style.color = "white";
document.getElementById('button1').style.color = "#47597E";
document.getElementById('button2').style.color = "#47597E";
document.getElementById('button3').style.color = "#47597E";
document.getElementById('text_p').style.backgroundColor = "#A2DBFA";
document.getElementById('button6').innerHTML = "Dark Mode";
}
現在說我想恢復到舊設定,我需要按鈕來執行相反的操作,并在模式和點擊之間來回切換。任何幫助表示贊賞!
ps - 我知道這對你們中的一些人來說很痛苦,但我正在學習!
uj5u.com熱心網友回復:
你可以做一個功能來切換主題,所以如果主題當前是暗的,它就會變亮,如果它是亮的,它就會變暗
// keeps track of whether the theme is dark or light
let darkMode = false
function ToggleTheme() {
// if the theme is currently dark, set it to light
if(darkMode) {
// set the colors for the light theme
// update the dark mode variable
darkMode = false
}
// otherwise, set it to dark
else {
document.body.style.backgroundColor = "#DBE6FD";
document.getElementById('button_circle').style.color = "white";
document.getElementById('button1').style.color = "#47597E";
document.getElementById('button2').style.color = "#47597E";
document.getElementById('button3').style.color = "#47597E";
document.getElementById('text_p').style.backgroundColor = "#A2DBFA";
document.getElementById('button6').innerHTML = "Dark Mode";
darkMode = true
}
}
<button id="button6" type="button" class="btns"
onclick="ToggleTheme()">Light Mode</button>
uj5u.com熱心網友回復:
目前,如果您不熟悉CSS. 這是另一種方法。
將狀態存盤在常量中
const LIGHT_MODE = {
backgroundColor: "#DBE6FD",
button_circleColor: "white",
button1Color: "#47597E",
button2Color: "#47597E",
button3Color: "#47597E",
text_pBackgroundColor: "#A2DBFA",
}
const DARK_MODE = {
backgroundColor: "...",
button_circleColor: "...",
button1Color: "...",
button2Color: "...",
button3Color: "...",
text_pBackgroundColor: "...",
}
function LightTheme() {
const button6 = document.getElementById('button6');
let theme = undefined;
if (button6.innerHTML === "Dark Mode") {
button6.innerHTML = "Light Mode";
theme = LIGHT_MODE;
} else {
button6.innerHTML = "Dark Mode";
theme = DARK_MODE;
}
document.body.style.backgroundColor = theme.backgroundColor;
document.getElementById('button_circle').style.color = theme.button_circleColor;
document.getElementById('button1').style.color = theme.button1Color;
document.getElementById('button2').style.color = theme.button2Color;
document.getElementById('button3').style.color = theme.button3Color;
document.getElementById('text_p').style.backgroundColor = theme.text_pBackgroundColor;
}
此外,CSS這樣可以更容易實作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/508663.html
上一篇:如何從物件陣列中獲取交易總和
