2 回答
TA贡献1816条经验 获得超4个赞
为什么不调整你的 css,这样你只改变一个?保持卫生。
function toggleDark() {
const body = document.querySelector('body');
if (body.classList.contains('dark')) {
body.classList.remove('dark');
} else {
body.classList.add('dark');
}
}
document.querySelector('#darkmode').addEventListener('click', toggleDark);
body {
background-color: #c0c0c0;
}
body.dark {
background-color: #272727;
}
.container1 {
width: fit;
background-color: lightblue;
height: fit;
color: green;
}
body.dark .container1 {
width: fit;
background-color: yellow;
height: fit;
color: red;
}
.container2 {
width: fit;
background-color: black;
height: fit;
color: white;
}
body.dark .container2 {
width: fit;
background-color: white;
height: fit;
color: black;
}
.button1 {
background-color: #c0c0c0;
color: black;
border-radius: 25px;
border: 1px solid black
}
body.dark .button1 {
background-color: #white;
color: black;
border-radius: 25px;
border: 1px solid black
}
<div class="container1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div><br />
<div class="container2">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div><br />
<button id="darkmode" class="button1">🌕 Lights Off!!</button>
TA贡献1826条经验 获得超6个赞
选择按钮并监听事件click。每当您单击一个按钮时,您都会想要调用一个函数,该函数循环遍历您指定的元素并用于向这些元素classList.toggle('dark')添加或删除.dark类。
const button = document.querySelector('#darkmode');
const elements = document.querySelectorAll('body, .container1, .button1');
button.addEventListener('click', () => {
for (const element of elements) {
element.classList.toggle('dark');
}
});
但是使用 CSS 的力量可能更容易。像这样:
.container1 {
background-color: lightblue;
}
.dark .container1 {
background-color: yellow;
}
现在,您只需dark在所有元素的父元素(例如 )上添加或删除类,body即可打开或关闭深色模式。
const button = document.querySelector('#darkmode');
button.addEventListener('click', () => {
document.body.classList.toggle('dark');
});
哦,小旁注:fit不是该属性的有效值width。检查MDN以获取有效值。
添加回答
举报