1

我有以下 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 类名更改为黑色
4

3 回答 3

1

尝试这个:

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/else 来处理从一种颜色到另一种颜色的变化。

于 2013-10-21T16:10:16.797 回答
1
function setThemeColor(button) {
    var newColor = button.className == "Blue" ? "Black" : "Blue";
    localStorage.themeColor = newColor;
    document.getElementsByTagName('html')[0].className = newColor;
}
于 2013-10-21T16:10:30.103 回答
1

我建议:

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';
}

JS 小提琴演示

于 2013-10-21T16:11:13.783 回答