我正在嘗試添加暗模式功能并且已經成功,問題是暗/亮模式之間的切換僅針對 html/css 的主體
:root {
--blue: rgb(13, 59, 105);
--white: rgb(255, 254, 254);
}
body {
background: var(--background-color);
color: var(--text-color);
font-weight: var(--font-weight);
}
body.light {
--background-color: var(--white);
--text-color: var(--blue);
--image: url("./day-forrest.jpg");
}
body.dark {
--background-color: var(--blue);
--text-color: var(--white);
--image: url("./night-forrest.jpg");
}
.title-heading {
text-align: center;
margin: 4rem 0 0 0;
font-size: 40px;
color: var(--text-color);
}
nav {
display: flex;
justify-content: space-evenly;
align-items: center;
background: var(--text-color);
}
nav a {
text-decoration: none;
font-weight: 500;
color: var(--background-color);
}
.background-image {
width: 100%;
height: 200px;
background-position: center;
background-repeat: no-repeat;
background-size: 1100px;
background-image: var(--image);
}
.title-heading {
text-align: center;
margin: 4rem 0 1rem 0;
font-size: 40px;
}
.subtitle {
width: 40%;
margin: 2rem auto;
line-height: 1.6;
text-align: center;
}
p {
width: 40%;
margin: 2rem auto;
line-height: 1.6;
}
從“反應”匯入反應;匯入“./styles.css”;
const DarkMode = () => {
let clickedClass = "clicked";
const body = document.body;
const lightMode = "light";
const darkMode = "dark";
let theme;
if (localStorage) {
theme = localStorage.getItem("theme");
}
if (theme === lightMode || theme === darkMode) {
body.classList.add(theme);
} else {
body.classList.add(lightMode);
}
const switchTheme = (e) => {
if (theme === darkMode) {
body.classList.replace(darkMode, lightMode);
e.target.classList.remove(clickedClass);
localStorage.setItem("theme", "light");
theme = lightMode;
} else {
body.classList.replace(lightMode, darkMode);
e.target.classList.add(clickedClass);
localStorage.setItem("theme", "dark");
theme = darkMode;
}
};
return (
<button
className={theme === "dark" ? clickedClass : ""}
id="darkMode"
onClick={(e) => switchTheme(e)}
></button>
);
};
export default DarkMode;
這個問題的一個解決方案是在淺色模式下有作業經驗、愛好和聯系這 3 個單獨的標題顏色,并且在深色模式下它們都變成白色,而不是整個程序中只有藍色和白色的 2 個可變顏色選項頁。
--blue: rgb(13, 59, 105); --white: rgb(255, 254, 254);
在此先感謝沙盒鏈接在這里https://codesandbox.io/s/dark-mode-issue-14-11-22-f0edup?file=/src/AboutPage/styles.css
uj5u.com熱心網友回復:
您可以使用
組合器分別選擇body
in light 和 dark 的孩子。
更多關于
CSS 中的組合器
這樣,您可以自定義它們在每種顏色模式下的外觀。
例子
body.light .title-heading {
color: green;
}
body.dark .title-heading {
color: white;
}
此示例使.title-heading
hascolor: green
處于亮模式和color: white
暗模式。
您可以使用此方法通過 CSS 為其他元素添加自定義樣式。
希望這會有所幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533606.html