How do I change the background color with JavaScript?

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

    This is simple coding for changing background using javascript

    <body onLoad="document.bgColor='red'">
    
    0 讨论(0)
  • 2020-11-22 14:49
    <!DOCTYPE html>
    <html>
    <body>
    <select name="" id="select" onClick="hello();">
        <option>Select</option>
        <option style="background-color: #CD5C5C;">#CD5C5C</option>
        <option style="background-color: #F08080;">#F08080</option>
        <option style="background-color: #FA8072;">#FA8072</option>
        <option style="background-color: #E9967A;">#E9967A</option>
        <option style="background-color: #FFA07A;">#FFA07A</option>
    </select>
    <script>
    function hello(){
    let d = document.getElementById("select");
    let text = d.options[d.selectedIndex].value;
    document.body.style.backgroundColor=text;
    }
    </script>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 14:51

    I wouldn't really class this as "AJAX". Anyway, something like following should do the trick:

    document.body.style.backgroundColor = 'pink';
    
    0 讨论(0)
  • 2020-11-22 14:52

    function pink(){ document.body.style.background = "pink"; }
    function sky(){ document.body.style.background = "skyblue"; }
    <p onclick="pink()" style="padding:10px;background:pink">Pink</p>
    <p onclick="sky()" style="padding:10px;background:skyblue">Sky</p>

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

    You can change background of a page by simply using:

    document.body.style.background = #000000; //I used black as color code
    

    However the below script will change the background of the page after every 3 seconds using setTimeout() function:

    $(function() {
                var colors = ["#0099cc","#c0c0c0","#587b2e","#990000","#000000","#1C8200","#987baa","#981890","#AA8971","#1987FC","#99081E"];
    
                setInterval(function() { 
                    var bodybgarrayno = Math.floor(Math.random() * colors.length);
                    var selectedcolor = colors[bodybgarrayno];
                    $("body").css("background",selectedcolor);
                }, 3000);
            })
    

    READ MORE

    DEMO

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

    Modify the JavaScript property document.body.style.background.

    For example:

    function changeBackground(color) {
       document.body.style.background = color;
    }
    
    window.addEventListener("load",function() { changeBackground('red') });
    

    Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.

    0 讨论(0)
提交回复
热议问题