[英]How can I make it so that clicking a button changes it's class name and the class name of my HTML tag?
I have the following HTML: 我有以下HTML:
<button class="Blue" id="theme" onclick="setThemeColor(this)">#</button>
And the following function: 并具有以下功能:
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
}
How can I make it so: 我怎么能这样做:
try this: 尝试这个:
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
}
However really you don't need to put the class on the button what you should do for the theme is set the class on the HTML tag like you're doing, and apply styles using that has the prefix since css will cascade. 但实际上你不需要把类放在按钮上你应该为主题做什么,就像你正在做的那样在HTML标签上设置类,并使用具有前缀的类来应用样式,因为css会级联。 EG:
例如:
html.blue button { color: blue }
So then the code would just look like this: 那么代码就像这样:
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;
}
Also, with my code (unlike the others) if you want to add a color you just add it to the array. 另外,使用我的代码(与其他代码不同)如果要添加颜色,只需将其添加到数组中即可。 The other way you have to start putting in a bunch of if/elses to handle going from one color to another.
另一种方式你必须开始放入一堆if / elses来处理从一种颜色到另一种颜色。
function setThemeColor(button) {
var newColor = button.className == "Blue" ? "Black" : "Blue";
localStorage.themeColor = newColor;
document.getElementsByTagName('html')[0].className = newColor;
}
I'd suggest: 我建议:
function setThemeColor(button) {
/* toggling between blue and black, means the className of the 'html'
element should be whatever the button's className was: */
document.getElementsByTagName('html')[0].className = button.className;
// changing the class to 'black' if it was 'blue', and to 'blue' if it wasn't:
button.className = button.className.indexOf('blue') === -1 ? 'blue' : 'black';
// setting the localStorage:
localStorage.themeColor = button.className.indexOf('blue') === -1 ? 'blue' : 'black';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.