How do I change the background color with JavaScript?

后端 未结 19 2652
春和景丽
春和景丽 2020-11-22 13:59

Anyone know a simple method to swap the background color of a webpage using JavaScript?

19条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 14:55

    I agree with the previous poster that changing the color by className is a prettier approach. My argument however is that a className can be regarded as a definition of "why you want the background to be this or that color."

    For instance, making it red is not just because you want it red, but because you'd want to inform users of an error. As such, setting the className AnErrorHasOccured on the body would be my preferred implementation.

    In css

    body.AnErrorHasOccured
    {
      background: #f00;
    }
    

    In JavaScript:

    document.body.className = "AnErrorHasOccured";
    

    This leaves you the options of styling more elements according to this className. And as such, by setting a className you kind of give the page a certain state.

提交回复
热议问题