[英]How do I properly structure a dark mode toggle using Javascript?
I've been trying to have my toggle trigger a dark mode on and off using JavaScript but clearly I'm doing something wrong.我一直在尝试使用 JavaScript 让我的切换触发暗模式打开和关闭,但显然我做错了。 I attempted to trigger it by applying the light class to my body and using addClassListener.
我试图通过将灯光 class 应用到我的身体并使用 addClassListener 来触发它。 Below is a simplified version of my code but i also plan on doing this on specific classes as well in order to change font and div colors in each different mode as well.
下面是我的代码的简化版本,但我也计划在特定类上执行此操作,以便在每种不同模式下也更改字体和 div colors。 Any suggestions?
有什么建议么?
HTML HTML
<label class="switch">
<input type="checkbox" checked>
<span id="slide" class="slider round"></span>
</label>
CSS CSS
body{
position: absolute;
top: 320px;
left: 0;
width: 100%;
height: 100%;
background-color: hsl(230, 17%, 14%);
z-index: -1;
}
body.light {
background-color: white;
}
Javascript Javascript
const checkbox = document.getElementById('slide');
checkbox.addEventListener('change', ()
==>{document.body.classList.toggle('light');
});
You are attempting to get the element by id
, but you have not defined any id
s in your snippet.您正在尝试通过
id
获取元素,但您尚未在代码段中定义任何id
。
<label class="switch">
<input type="checkbox" checked>
<span id="slider" class="slider round"></span>
</label>
Additionally, you're listening for a change
event on a span
element.此外,您正在侦听
span
元素上的change
事件。 The span
element will never fire a change event. span
元素永远不会触发更改事件。 If you change that to listen in the input
element, it should fire.如果您将其更改为在
input
元素中侦听,它应该会触发。 Documentation 文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.