我有以下HTML:
<button class="Blue" id="theme" onclick="setThemeColor(this)">#</button>
和以下功能:
function setThemeColor(button) {
localStorage.themeColor = // I need to set it here but I am not sure how
// if the class is Blue it needs to be Black
// if the class is Black it needs to be Blue
document.getElementsByTagName('html')[0].className = //
// I need to change the button class
}
我该怎么做:
如果按钮类是蓝色,则单击它会将类更改为黑色,而html类名将更改为蓝色
如果按钮类是黑色,则单击它会将类更改为蓝色,而html类名将更改为黑色
最佳答案
尝试这个:
var colors = ["Black", "Blue"];
function setThemeColor(button) {
localStorage.themeColor = colors[(colors.indexOf(button.className) + 1) % colors.length];
document.getElementsByTagName("html")[0].className = localStorage.themeColor;
button.className = localStorage.themeColor; //by the way you shouldn't need this if you did this more effectively in CSS
}
但是,实际上,您不需要将类放在按钮上,您应该像在进行操作那样在HTML标记上设置类,并使用带有前缀的样式应用样式,因为CSS会级联,因此您无需对主题进行操作。例如:
html.blue button { color: blue }
因此,代码如下所示:
var colors = ["Black", "Blue"];
function setThemeColor(button) {
var html = document.documentElement;
var newColor = colors[(colors.indexOf(html.className) + 1) % colors.length];
localStorage.themeColor = newColor;
html.className = newColor;
}
另外,使用我的代码(与其他代码不同),如果要添加颜色,只需将其添加到数组中即可。另一种方法是,必须开始放入一堆if / els,以处理从一种颜色到另一种颜色的变化。