Setting document.body.className as a variable

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

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

    Or whatever your color class definitions are.

提交回复
热议问题