How do I change the background color with JavaScript?

后端 未结 19 2286
春和景丽
春和景丽 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:42

    You can do it in following ways STEP 1

       var imageUrl= "URL OF THE IMAGE HERE";
       var BackgroundColor="RED"; // what ever color you want
    

    For changing background of BODY

    document.body.style.backgroundImage=imageUrl  //changing bg image
    document.body.style.backgroundColor=BackgroundColor //changing bg color
    

    To change an element with ID

    document.getElementById("ElementId").style.backgroundImage=imageUrl
    document.getElementById("ElementId").style.backgroundColor=BackgroundColor 
    

    for elements with same class

       var elements = document.getElementsByClassName("ClassName")
            for (var i = 0; i < elements.length; i++) {
                elements[i].style.background=imageUrl;
            }
    

提交回复
热议问题