Setting document.body.className as a variable

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

    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 bodyColor and classNames variables are in global scope.

提交回复
热议问题