通过JavaScript向您的网站添加Darkmode
我是一个初学者,我为自己设定了一个挑战:使用JS功能为我的投资组合创建一个Darkmode。
html:
<nav class="navbar dark-mode" id="navbar">
<ul class="navbar_links">
<li class="navbar_link first"><a href="#">Accueil</a></li>
<li class="navbar_link second"><a href="#">Service</a></li>
<li class="navbar_link third"><a href="#">Mission</a></li>
<li class="navbar_link fourth"><a href="#">Portfolio</a></li>
<li class="navbar_link fifth"><a href="#">Contact</a></li>
</ul>
<img id="lightModeIcon" src="img/light-mode.png" alt="">
</nav>
javaScript:,
function lightMode() {
const lightModeIcon = document.getElementById('lightModeIcon');
const navbar = document.getElementById('navbar');
if (navbar.classList.contains("dark-mode")) {
lightModeIcon.addEventListener('click', () => {
navbar.classList.replace("dark-mode", "light-mode");
lightModeIcon.src = "img/dark-mode.png";
})
} else {
lightModeIcon.addEventListener('click', () => {
navbar.classList.replace("light-mode", "dark-mode");
lightModeIcon.src = "img/light-mode.png";
})
}
}
lightMode();
但我有问题。我使用“如果... esle”。
“如果”零件有效。但是“其他”部分不起作用。
通常,如果用户已经单击了Darkmode按钮,则我的#navbar不包含“ Dark-Mode”类,而是“ .light-Mode”。因此,“其他”部分应该运行。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑 代码正在运行时。
Dark-Mode
将硬式编码为HTMLLightMode
在页面加载时被调用。如果
语句绑定两个事件侦听器之一,当功能运行时,
else
分支的条件永远不正确。编写一个单事件侦听器,总是将其绑定到按钮,测试当前状态内部事件侦听器。
请注意,您可以基于此选择了您的方案,而不是将UI完全独立的UI与用户系统的其余部分相关。
Think about when the code is running.
dark-mode
is hard coded into the HTMLlightMode
is called when the page loads.if
statement binds one of the two event listenersThe condition for the
else
branch is never true when the function runs.Write a single event listener, always bind it to the button, test what the current state is inside the event listener.
Note that you can detect the user's OS mode has pick your scheme based on that instead of having a completely separate UI to the rest of the user's system.
您正在运行此功能一次(大概是在加载页面时),它将一次评估条件并注册单个事件侦听器(将课程设置为Dark Mode,或者一个侦听器这将其设置为光模式)。因此,点击将完成整个工作。
取而代之的是,您应该在活动侦听器中移动IF-ELSE检查,以便在单击时检查课程。这可能很简单,就像倒置功能的第三行和第四行一样简单,例如:
You're running this function once (presumably when the page is loaded), which will evaluate the condition once and register a single event listener (either the one that sets the class to dark mode, or the one that sets it to light mode). As such, clicks will do the same thing for the entirety.
Instead you should move your if-else check inside the event listener, such that you're checking the classes at the time of the click. This can be as simple as inverting the third and fourth lines of your function, e.g.: