How do I change the background color with JavaScript?

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

    You can change background of a page by simply using:

    function changeBodyBg(color){
        document.body.style.background = color;
    }
    

    Read more @ Changing the Background Color

    0 讨论(0)
  • 2020-11-22 14:40

    if you wish to use a button or some other event, just use this in JS:

    document.querySelector("button").addEventListener("click", function() {
    document.body.style.backgroundColor = "red";
    });
    
    0 讨论(0)
  • 2020-11-22 14:41

    Css approach:

    If you want to see continuous colour, use this code:

    body{
        background-color:black;
        animation: image 10s infinite alternate;
        animation:image 10s infinite alternate;
        animation:image 10s infinite alternate;
    }
    
    @keyframes image{
        0%{
    background-color:blue;
    }
    25%/{
        background-color:red;
    }
    50%{
        background-color:green;
    }
    75%{
    
        background-color:pink;
    }
    100%{
        background-color:yellow;
        }
      }  
    

    If you want to see it faster or slower, change 10 second to 5 second etc.

    0 讨论(0)
  • 2020-11-22 14:41

    Alternatively, if you wish to specify the background color value in rgb notation then try

    document.getElementById("yourid").style.backgroundColor = 'rgb(' + a + ',' + b + ',' + c + ')';
    

    where a,b,c are the color values

    Example:

    document.getElementById("yourid").style.backgroundColor = 'rgb(224,224,224)';
    
    0 讨论(0)
  • 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;
            }
    
    0 讨论(0)
  • 2020-11-22 14:47

    I would prefer to see the use of a css class here. It avoids having hard to read colors / hex codes in javascript.

    document.body.className = className;
    
    0 讨论(0)
提交回复
热议问题