¿Cómo cambio el color de fondo con JavaScript?


¿Alguien conoce un método simple para intercambiar el color de fondo de una página web usando JavaScript?

Author: mc10, 2008-10-13

16 answers

Modifica la propiedad JavaScript document.body.style.background.

Por ejemplo:

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

<BODY onload="changeBackground('red');">

Nota: esto depende un poco de cómo se junta su página, por ejemplo, si está utilizando un contenedor DIV con un color de fondo diferente, necesitará modificar el color de fondo de ese en lugar del cuerpo del documento.

 164
Author: Nathan Arthur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-15 21:45:16

No necesita AJAX para esto, solo un script java simple que establezca la propiedad background-color del elemento body, como esto:

document.body.style.backgroundColor = "#AA0000";

Si desea hacerlo como si fuera iniciado por el servidor, tendría que sondear el servidor y luego cambiar el color en consecuencia.

 41
Author: Simon Lehmann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-13 14:27:56

Estoy de acuerdo con el póster anterior en que cambiar el color por className es un enfoque más bonito. Mi argumento sin embargo es que un className puede ser considerado como una definición de "por qué quieres que el fondo sea este o aquel color."

Por ejemplo, hacerlo rojo no es solo porque lo quieres rojo, sino porque quieres informar a los usuarios de un error. Como tal, establecer el nombre de clase AnErrorHasOccured en el cuerpo sería mi implementación preferida.

En css

body.AnErrorHasOccured
{
  background: #f00;
}

En JavaScript:

document.body.className = "AnErrorHasOccured";

Esto le deja las opciones de estilo más elementos de acuerdo con este className. Y como tal, al establecer un className le das a la página un cierto estado.

 18
Author: Martin Kool,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-16 13:17:04

AJAX obtiene datos del servidor usando Javascript y XML de manera asíncrona. A menos que quiera descargar el código de color del servidor, ¡eso no es lo que realmente busca!

Pero de lo contrario puede establecer el fondo CSS con Javascript. Si estás usando un framework como jQuery, será algo como esto:

$('body').css('background', '#ccc');

De lo contrario, esto debería funcionar:

document.body.style.background = "#ccc";
 9
Author: Oli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-13 14:30:23

Puede hacerlo de las siguientes maneras PASO 1

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

Para cambiar el fondo de CUERPO

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

Para cambiar un elemento con ID

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

Para elementos de la misma clase

   var elements = document.getElementsByClassName("ClassName")
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.background=imageUrl;
        }
 4
Author: Vignesh Subramanian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-26 05:10:11

Realmente no clasificaría esto como "AJAX". De todos modos, algo como seguir debería hacer el truco:

document.body.style.backgroundColor = 'pink';
 3
Author: Duncan Smart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-13 14:27:50

Enfoque Css:

Si quieres ver color continuo, usa este código:

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;
    }
  }  

Si quieres verlo más rápido o más lento, cambia 10 segundos a 5 segundos, etc.

 3
Author: Deniz.parlak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-04 10:34:00

Puede cambiar el fondo de una página simplemente usando:

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

Sin embargo, el siguiente script cambiará el fondo de la página después de cada 3 segundos usando la función setTimeout ():

$(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);
        })

LEER MÁS

DEMO

 2
Author: defau1t,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-02 11:27:23

Preferiría ver el uso de una clase css aquí. Evita tener códigos de colores / hex difíciles de leer en javascript.

document.body.className = className;
 2
Author: redsquare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-28 12:27:08

Esto cambiará el color de fondo de acuerdo con la elección del usuario seleccionado en el menú desplegable:

function changeBG() {
  var selectedBGColor = document.getElementById("bgchoice").value;
  document.body.style.backgroundColor = selectedBGColor;
}
<select id="bgchoice" onchange="changeBG()">
    <option></option>
    <option value="red">Red</option>
    <option value="ivory">Ivory</option>
    <option value="pink">Pink</option>
</select>
 2
Author: Ritam Das,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-16 13:19:50

Agregue este elemento script a su elemento body, cambiando el color como desee:

<body>
  <p>Hello, World!</p>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#ff0000";  // red
  </script>
</body>
 1
Author: james.garriss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-01 12:16:20

Pero le gustaría configurar el color del cuerpo antes de que exista el elemento <body>. De esa manera tiene el color correcto desde el principio.

<script>
    var myColor = "#AAAAAA";
    document.write('\
        <style>\
            body{\
                background-color: '+myColor+';\
            }\
        </style>\
    ');
</script>

Esto puede ponerlo en el <head> del documento o en su archivo js.

Aquí hay un buen color para jugar.

var myColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
 0
Author: gaby de wilde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-03 02:04:13

Sugeriría el siguiente código:

<div id="example" onClick="colorize()">Click on this text to change the
background color</div>
<script type='text/javascript'>
function colorize() {
var element = document.getElementById("example");
element.style.backgroundColor='#800';
element.style.color='white';
element.style.textAlign='center';
}
</script>
 0
Author: joel hills,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-16 13:20:31

Si desea usar un botón o algún otro evento, simplemente use esto en JS:

document.querySelector("button").addEventListener("click", function() {
document.body.style.backgroundColor = "red";
});
 0
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-22 11:14:57

Puede cambiar el fondo de una página simplemente usando:

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

Read more @ Cambiando el Color de fondo

 0
Author: jonathan klevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-28 05:11:38

Esta es una codificación simple para cambiar el fondo usando javascript

<body onLoad="document.bgColor='red'">
 -2
Author: Shahnawaz Alam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-13 09:08:33