Javascript 将 document.body.className 设置为变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2125993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:51:09  来源:igfitidea点击:

Setting document.body.className as a variable

javascriptvariables

提问by Choy

This is my code to switch the class of my body tag when a user clicks a link.

这是我的代码,用于在用户单击链接时切换 body 标签的类。

function switchBodyColor() {
    if (document.body.className == 'blue')
        document.body.className = 'red';
    else if (document.body.className == 'red')
        document.body.className = 'green';
    else if (document.body.className == 'green')
        document.body.className = 'blue';
}

I want to set the resulting color as a variable called bodyColor. So if the body class is "blue" and the user clicks and switches it to "red" I want to store red as a variable (bodyColor) for other uses later on. Or better yet, set document.body.className as a variable itself and then switch out document.body.className in the switchBodyColor() function with that variable.

我想将结果颜色设置为一个名为 bodyColor 的变量。因此,如果 body 类是“blue”并且用户单击并将其切换为“red”,我想将红色存储为变量 (bodyColor) 以供以后使用。或者更好的是,将 document.body.className 本身设置为变量,然后使用该变量在 switchBodyColor() 函数中切换出 document.body.className。

I thought something along the lines of:

我想到了以下几点:

    if (document.body.className == 'blue')
        document.body.className = 'red',
        var bodyColor = red;

or

或者

var bodyColor = document.body.className

to set the body class as a variable.

将主体类设置为变量。

Of course neither of those two options work. ^_^; How can I accomplish either (or both) of the above?

当然,这两个选项都不起作用。^_^; 我如何才能完成上述任一(或两者)?

回答by Jeff B

You need your variable to be global:

你需要你的变量是全局的:

var bodyColor = 'red';  // Global var, initialized to your first color class

function switchBodyColor() {
    if (document.body.className == 'blue')
        document.body.className = 'red';
    else if (document.body.className == 'red')
        document.body.className = 'green';
    else if (document.body.className == 'green')
        document.body.className = 'blue';


    bodyColor = document.body.className;
    alert(bodyColor);
}

In your other example, you also need to put quotes around your color string:

在您的另一个示例中,您还需要在颜色字符串周围加上引号:

 bodyColor = "red";



Another way to do this might be to number your color classes, which will let you use simple arithmetic to change your classes and allows you to easily change the number of classes you are cycling through.



另一种方法可能是为您的颜色类别编号,这将让您使用简单的算术来更改您的类别,并允许您轻松更改您正在循环的类别数量。

var colorNum = 0;
var totalColors = 3;

function switchBodyColor() {
    colorNum = (colorNum+1)%totalColors;
    document.body.className = 'color'+colorNum;
}

You css would be:

你的 css 将是:

.color0 { background-color: blue; }
.color1 { background-color: red; }
.color2 { background-color: green; }

Or whatever your color class definitions are.

或者无论您的颜色类定义是什么。

回答by Doug Neiner

You could store the colors in an array, then by manipulation always use the first color in the array as the current color:

您可以将颜色存储在数组中,然后通过操作始终使用数组中的第一种颜色作为当前颜色:

var bodyColors = ['blue','red','green'];

function switchBodyColor(){
   bodyColors.push(bodyColors.shift()); // Move first item to the end
   document.body.className = bodyColors[0];
}

And then anywhere you need it in your app, just call:

然后在您的应用程序中任何需要它的地方,只需调用:

bodyColors[0]; // Will refer to the current body class

Optional Check for Initial State

可选的初始状态检查

The previous code assumes your bodyelement always starts with blue. If that is not the case, you could add this one-time run code right below the switchBodyColor()function:

前面的代码假定您的body元素始终以blue. 如果不是这种情况,您可以在switchBodyColor()函数下方添加此一次性运行代码:

for(var i=0; i<bodyColors.length; i++){
   if(document.body.className == bodyColors[i]) break;
   bodyColors.push(bodyColors.shift());
}

Additional Explanation

附加说明

Since you want the colors to always rotate in the same order, it would make sense to use an Array because its order is always honored. Howeversince there is no "indexOf" in at least IE7 and below, we have no way of matching the current color to its position in the array without a loop.

由于您希望颜色始终以相同的顺序旋转,因此使用 Array 是有意义的,因为它的顺序总是受到尊重。但是,由于indexOf至少在 IE7 及以下版本中没有“ ”,因此我们无法在没有循环的情况下将当前颜色与其在数组中的位置进行匹配。

This is where the Array.shiftand Array.pushcommands come into play. Array.shiftremoves the firstelement in the array, and returns it. Array.pushtakes what is passed to it, and "pushes" it onto the endof the array. By combining the two methods together we can take the first item and move it to the end, creating a carousel of sorts:

这就是Array.shiftArray.push命令发挥作用的地方。Array.shift删除数组中的第一个元素,并返回它。Array.push获取传递给它的内容,并将其“推送”到数组的末尾。通过将这两种方法结合在一起,我们可以将第一个项目移到最后,创建各种轮播:

var c = [1,2,3];
c.push(c.shift());
console.log(c); // Outputs [2,3,1]
c.push(c.shift());
console.log(c); // Outputs [3,1,2]
c.push(c.shift());
console.log(c); // Outputs [1,2,3]

Thus, the order is always honored and the first element is always set to what we want, thus bodyColor[0]is always the current color.

因此,始终遵循顺序,并且第一个元素始终设置为我们想要的,因此bodyColor[0]始终是当前颜色。

回答by Jacob Relkin

I would write a function and an array for this:

我会为此编写一个函数和一个数组:

var classNames = { 'blue': 'red', 'red': 'green', 'green': 'blue' };

function setBodyClass( className ) {
   document.body.className = className;
   bodyColor = className;
}

function switchBodyColor() {
   var newClass = classNames[ document.body.className ];
   if( newClass.length ) { //body.className is in the array.
       setBodyClass( newClass );
   }
}

This of course is assuming that the bodyColorand classNamesvariables are in global scope.

这当然是假设bodyColorclassNames变量在全局范围内。

回答by rahul

If you want to set a global variable then you will have to declare it outside the function, so that your other functions can access it. So it would be like

如果要设置全局变量,则必须在函数外部声明它,以便其他函数可以访问它。所以它会像

var bodyColor;

function switchBodyColor() {
    if (document.body.className == 'blue')
    {
        document.body.className = 'red';
    }
    else if (document.body.className == 'red')
    {
        document.body.className = 'green';
    }
    else if (document.body.className == 'green')
    {
        document.body.className = 'blue';
    } 

    bodyColor = document.body.className;
}

You can also replace the if else if statement with a switch case block.

您还可以用 switch case 块替换 if else if 语句。