我正在尝试添加一个暗模式功能,并且已经成功了,问题是暗/光模式之间的切换只针对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;
}
进口反应从“反应”;进口“./traces.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种不同的蓝色和白色选项。
-蓝色: rgb(13,59,105);-白色: rgb(255,254,254);
谢谢您,沙箱链接在这里,https://codesandbox.io/s/dark-mode-issue-14-11-22-f0edup?file=/src/AboutPage/styles.css
发布于 2022-11-15 02:21:00
您可以使用组合器分别在光线和黑暗中选择body的子级。
通过这种方式,您可以自定义它们在每种颜色模式中的外观。
示例
body.light .title-heading {
color: green;
}
body.dark .title-heading {
color: white;
}此示例使.title-heading在光模式下具有color: green,在暗模式下具有color: white。
您可以使用这种方法为其他元素添加自定义样式,所有这些都是通过CSS实现的。
希望这能帮上忙!
https://stackoverflow.com/questions/74439804
复制相似问题