2 回答
TA贡献1785条经验 获得超8个赞
您需要将原始背景颜色设置为“浅色主题”背景并将=if 语句中的更改为==。此外,您只需为具有a标签的第一个元素设置文本颜色。把你的代码改成这样:
document.getElementById("theme_change").onclick = function () {
if (document.body.style.backgroundColor == "#000") {
document.body.style.backgroundColor = "#f5deb3";
document.getElementsByTagName("a")[0].style.color = "#000";
document.getElementsByTagName("a")[0].style.borderColor = "#000";
document.getElementsByTagName("a")[1].style.color = "#000";
document.getElementsByTagName("a")[1].style.borderColor = "#000";
document.getElementById("theme_change").innerText = "Light Theme";
} else if (document.body.style.backgroundColor = "#f5deb3") {
document.body.style.backgroundColor == "#000";
document.getElementsByTagName("a")[0].style.color = "#f5deb3";
document.getElementsByTagName("a")[0].style.borderColor = "#f5deb3";
document.getElementsByTagName("a")[1].style.color = "#f5deb3";
document.getElementsByTagName("a")[1].style.borderColor = "#f5deb3";
document.getElementById("theme_change").innerText = "Dark Theme";
}
}
TA贡献1807条经验 获得超9个赞
您的代码几乎没有缺点。
document.body.style.backgroundColor 给出格式为“rgb”而不是“hex”的颜色字符串。
在if语句中使用条件时,请始终使用==或===代替=。
因此,此代码应该适合您:
document.getElementById("theme_change").onclick = function () {
if (document.body.style.backgroundColor === "" || document.body.style.backgroundColor === "rgb(0, 0, 0)") {
document.body.style.backgroundColor = "#f5deb3";
document.getElementsByTagName("a")[0].style.color = "#000";
document.getElementsByTagName("a")[0].style.borderColor = "#000";
document.getElementById("theme_change").innerText = "Light Theme";
} else if (document.body.style.backgroundColor === "rgb(245, 222, 179)") {
document.body.style.backgroundColor = "#000";
document.getElementsByTagName("a")[0].style.color = "#f5deb3";
document.getElementsByTagName("a")[0].style.borderColor = "#f5deb3";
document.getElementById("theme_change").innerText = "Dark Theme";
}
}
<div id="buttons">
<a href="#" id="color_change" class="btn">Change Color</a>
<a href="#" id="theme_change" class="btn">Light Theme</a>
</div>
添加回答
举报