【发布时间】:2022-01-16 01:38:47
【问题描述】:
我正在尝试在我的网站上进行深色/浅色主题切换。 SVG 文件在每次点击时来回切换,但主题不是每次点击都会切换。
前两次点击 - 主题改变如预期。
第三次和第四次点击 - 每次点击时 SVG 图像仍会改变,但主题不会改变
第五次和第六次点击 - 主题按预期变化,循环重复
HTML:
<div id="themes">
<img id="current-theme">
</div>
CSS:
body{
background-color: #ccc;
}
#themes {
text-align: right;
margin-right: 10em;
margin-top: 2em;
transform: scale(1.5);
cursor: pointer;
}
.dark-mode {
background-color: rgb(65, 65, 65);
transition: background-color 0.5s ease;
h1 {
color: white;
}
h3 {
color: white;
}
button {
background-color: white;
color: black;
}
}
.light-mode {
background-color: #ccc;
transition: background-color 0.5s ease;
h1 {
color: var(--primary-color);
}
h3 {
color: black;
}
button {
background-color: black;
color: white;
}
}
Javascript:
//default theme is light
document.getElementById("current-theme").src = "images/moon.svg"
var currentTheme = document.getElementById("current-theme");
currentTheme.setAttribute("onClick", "toDarkTheme()");
var theme = document.body;
function toDarkTheme() {
document.getElementById("current-theme").src = "images/sun.svg";
theme.classList.toggle("dark-mode");
//currentTheme.removeAttribute("onClick");
currentTheme.setAttribute("onClick", "toLightTheme()");
}
function toLightTheme() {
document.getElementById("current-theme").src = "images/moon.svg";
theme.classList.toggle("light-mode");
//currentTheme.removeAttribute("onClick");
currentTheme.setAttribute("onClick", "toDarkTheme()");
}
我在 jsfiddle 中包含了一个代码链接,这样您就可以准确地看到正在发生的事情。感谢您提供的任何帮助/建议!
【问题讨论】:
-
我不禁认为拥有一个单击处理程序来检查当前主题并切换它会更容易。而不是每次点击都设置一个新的点击事件处理程序。
标签: javascript svg setattribute