Setting document.body.className as a variable

后端 未结 4 722
难免孤独
难免孤独 2021-01-06 04:22

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

function switchBodyColor() {
    if (document.body.className == \'blue\')
              


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-06 04:47

    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 body element always starts with blue. If that is not the case, you could add this one-time run code right below the switchBodyColor() function:

    for(var i=0; i

    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. However since 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.

    This is where the Array.shift and Array.push commands come into play. Array.shift removes the first element in the array, and returns it. Array.push takes what is passed to it, and "pushes" it onto the end of 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:

    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.

提交回复
热议问题