如何用JavaScript改变背景颜色?

时间:2022-07-09 00:39:52

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

有人知道用JavaScript交换网页背景颜色的简单方法吗?

16 个解决方案

#1


156  

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

修改JavaScript属性document.body.style.background。

For example:

例如:

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

<BODY onload="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.

注意:这确实取决于页面的布局方式,例如,如果使用不同背景颜色的DIV容器,则需要修改页面的背景颜色,而不是文档主体。

#2


40  

You don't need AJAX for this, just some plain java script setting the background-color property of the body element, like this:

这里不需要AJAX,只是一些普通的java脚本设置了body元素的背景色属性,比如:

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

If you want to do it as if it was initiated by the server, you would have to poll the server and then change the color accordingly.

如果您想让它看起来像服务器发起的,那么您必须轮询服务器,然后相应地更改颜色。

#3


18  

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."

我同意前面的海报,根据类名改变颜色是一种更漂亮的方法。然而,我的论点是,className可以被视为“为什么希望背景是这个或那个颜色”的定义。

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.

例如,将它设置为红色不仅是因为您希望它是红色的,还因为您希望通知用户错误。因此,在主体上设置className anerrorhas将是我的首选实现。

In css

在css中

body.AnErrorHasOccured
{
  background: #f00;
}

In JavaScript:

在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.

这为您提供了根据这个类名样式化更多元素的选项。因此,通过设置className,你就给了页面一个特定的状态。

#4


9  

AJAX is getting data from the server using Javascript and XML in an asynchronous fashion. Unless you want to download the colour code from the server, that's not what you're really aiming for!

AJAX以异步方式使用Javascript和XML从服务器获取数据。除非您想从服务器上下载颜色代码,否则这不是您真正想要的!

But otherwise you can set the CSS background with Javascript. If you're using a framework like jQuery, it'll be something like this:

但是,您可以使用Javascript设置CSS背景。如果你使用jQuery这样的框架,它会是这样的:

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

Otherwise, this should work:

否则,这应该工作:

document.body.style.background = "#ccc";

#5


3  

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

我不会把它归类为“AJAX”。不管怎么说,遵循这样的方法应该是有效的:

document.body.style.backgroundColor = 'pink';

#6


3  

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

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

#7


3  

Css approach:

Css的方法:

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.

如果你想看得更快或更慢,把10秒换成5秒。

#8


2  

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:

但是下面的脚本将使用setTimeout()函数每3秒改变页面的背景:

$(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

阅读更多的演示

#9


2  

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

我更喜欢在这里使用css类。它避免了在javascript中难以读取颜色/十六进制代码。

document.body.className = className;

#10


1  

This will change the background color according to the choice of user selected from the drop-down menu:

这将根据从下拉菜单中选择的用户改变背景颜色:

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>

#11


1  

Add this script element to your body element, changing the color as desired:

将此脚本元素添加到body元素中,根据需要更改颜色:

<body>
  <p>Hello, World!</p>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#ff0000";  // red
  </script>
</body>

#12


0  

But you would want to configure the body color before the <body> element exists. That way it has the right color from the get go.

但是您需要在元素存在之前配置body颜色。这样它就有了正确的颜色。

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

This you can put in the <head> of the document or in your js file.

您可以将其放入文档的或js文件中。

Here is a nice color to play with.

这是一个很好的颜色。

var myColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

#13


0  

I would suggest the following code:

我建议以下代码:

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

#14


0  

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

如果您希望使用按钮或其他事件,请在JS中使用:

document.querySelector("button").addEventListener("click", function() {
document.body.style.backgroundColor = "red";
});

#15


0  

You can change background of a page by simply using:

你只需使用:

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

Read more @ Changing the Background Color

阅读更多@改变背景颜色

#16


-2  

This is simple coding for changing background using javascript

这是使用javascript修改背景的简单代码

<body onLoad="document.bgColor='red'">

#1


156  

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

修改JavaScript属性document.body.style.background。

For example:

例如:

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

<BODY onload="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.

注意:这确实取决于页面的布局方式,例如,如果使用不同背景颜色的DIV容器,则需要修改页面的背景颜色,而不是文档主体。

#2


40  

You don't need AJAX for this, just some plain java script setting the background-color property of the body element, like this:

这里不需要AJAX,只是一些普通的java脚本设置了body元素的背景色属性,比如:

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

If you want to do it as if it was initiated by the server, you would have to poll the server and then change the color accordingly.

如果您想让它看起来像服务器发起的,那么您必须轮询服务器,然后相应地更改颜色。

#3


18  

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."

我同意前面的海报,根据类名改变颜色是一种更漂亮的方法。然而,我的论点是,className可以被视为“为什么希望背景是这个或那个颜色”的定义。

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.

例如,将它设置为红色不仅是因为您希望它是红色的,还因为您希望通知用户错误。因此,在主体上设置className anerrorhas将是我的首选实现。

In css

在css中

body.AnErrorHasOccured
{
  background: #f00;
}

In JavaScript:

在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.

这为您提供了根据这个类名样式化更多元素的选项。因此,通过设置className,你就给了页面一个特定的状态。

#4


9  

AJAX is getting data from the server using Javascript and XML in an asynchronous fashion. Unless you want to download the colour code from the server, that's not what you're really aiming for!

AJAX以异步方式使用Javascript和XML从服务器获取数据。除非您想从服务器上下载颜色代码,否则这不是您真正想要的!

But otherwise you can set the CSS background with Javascript. If you're using a framework like jQuery, it'll be something like this:

但是,您可以使用Javascript设置CSS背景。如果你使用jQuery这样的框架,它会是这样的:

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

Otherwise, this should work:

否则,这应该工作:

document.body.style.background = "#ccc";

#5


3  

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

我不会把它归类为“AJAX”。不管怎么说,遵循这样的方法应该是有效的:

document.body.style.backgroundColor = 'pink';

#6


3  

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

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

#7


3  

Css approach:

Css的方法:

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.

如果你想看得更快或更慢,把10秒换成5秒。

#8


2  

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:

但是下面的脚本将使用setTimeout()函数每3秒改变页面的背景:

$(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

阅读更多的演示

#9


2  

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

我更喜欢在这里使用css类。它避免了在javascript中难以读取颜色/十六进制代码。

document.body.className = className;

#10


1  

This will change the background color according to the choice of user selected from the drop-down menu:

这将根据从下拉菜单中选择的用户改变背景颜色:

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>

#11


1  

Add this script element to your body element, changing the color as desired:

将此脚本元素添加到body元素中,根据需要更改颜色:

<body>
  <p>Hello, World!</p>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#ff0000";  // red
  </script>
</body>

#12


0  

But you would want to configure the body color before the <body> element exists. That way it has the right color from the get go.

但是您需要在元素存在之前配置body颜色。这样它就有了正确的颜色。

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

This you can put in the <head> of the document or in your js file.

您可以将其放入文档的或js文件中。

Here is a nice color to play with.

这是一个很好的颜色。

var myColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

#13


0  

I would suggest the following code:

我建议以下代码:

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

#14


0  

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

如果您希望使用按钮或其他事件,请在JS中使用:

document.querySelector("button").addEventListener("click", function() {
document.body.style.backgroundColor = "red";
});

#15


0  

You can change background of a page by simply using:

你只需使用:

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

Read more @ Changing the Background Color

阅读更多@改变背景颜色

#16


-2  

This is simple coding for changing background using javascript

这是使用javascript修改背景的简单代码

<body onLoad="document.bgColor='red'">