Setting document.body.className as a variable

后端 未结 4 691
难免孤独
难免孤独 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:40

    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.

提交回复
热议问题