[英]Change background color between red and green every second
I'm trying to make a webpage change the background color every one second using JavaScript. 我正在尝试使用JavaScript每隔一秒使网页更改背景颜色。 I'm using setTimeout
but I can't figure out how to get my variable to change in the function. 我正在使用setTimeout
但我无法弄清楚如何在函数中更改变量。 Here's my code: 这是我的代码:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function changecolors() {
x = 1; // <-- I know this is wrong, I just don't know where to place it
var t = setTimeout("change()", 1000);
}
function change() {
while(x < 3) {
if(x = 1) {
color = "red";
x++;
} else if (x = 2) {
color = "green";
x = 1;
}
document.body.style.background = color;
}
}
</head>
<body onload="changecolors()">
</body>
</html>
There are several problems here. 这里有几个问题。 I'll just fix your code: 我只修复你的代码:
var x;
function changecolors() {
x = 1;
setInterval(change, 1000);
}
function change() {
if (x === 1) {
color = "red";
x = 2;
} else {
color = "green";
x = 1;
}
document.body.style.background = color;
}
Basically... 基本上...
setInterval
instead of setTimeout
. 您需要setInterval
而不是setTimeout
。 setTimeout
only executes once. setTimeout
只执行一次。 =
assigns, even in an if
statement. =
即使在if
语句中也会分配。 You need ==
(or better, ===
). 你需要==
(或更好, ===
)。 setTimeout
or setInterval
. 您不应该将字符串传递给setTimeout
或setInterval
。 Instead, pass a function. 相反,传递一个函数。 Another point of note: you shouldn't use the on*
attributes of HTML elements for event listeners, but especially not on <body>
, since you can do this in JavaScript instead, and be unobtrusive: 另一点需要注意的是:您不应该将HTML元素的on*
属性用于事件侦听器,尤其不应该用于<body>
,因为您可以在JavaScript中执行此操作,并且不引人注目:
window.onload = changecolors;
Of course, you could do it with fewer functions and no pollution of the global namespace . 当然, 您可以使用更少的功能并且不会污染全局命名空间 。
Blink fiddle: 眨眼小提琴:
http://jsfiddle.net/GolezTrol/R4c5P/1/ http://jsfiddle.net/GolezTrol/R4c5P/1/
Uses this function: 使用此功能:
function initBlink()
{
var state = false;
setInterval(function()
{
state = !state;
var color = (state?'red':'green');
document.getElementById('test').style.color = color;
}, 1000);
}
Uses closure to keep the state out of the global scope. 使用闭包来保持状态不在全局范围内。 Uses setInterval instead of setTimeout for repeated calling, although that may not be convenient. 使用setInterval而不是setTimeout来重复调用,虽然这可能不方便。 Both setInterval and setTimeout return a handle you can save and use to stop the timer, if you want, but since you didn't ask about that, I left it out for simplicity. 如果你愿意,setInterval和setTimeout都会返回一个你可以保存并用来停止计时器的句柄,但是由于你没有问过这个问题,为了简单起见,我把它留了下来。
The function just defines an anonymous callback that toggles a boolean and sets the color of a test div. 该函数只定义了一个匿名回调,它可以切换布尔值并设置测试div的颜色。
Also, consider doing it with CSS. 另外,考虑使用CSS。 Demo . 演示 。
@-webkit-keyframes blink {
0% { background:red; }
50% { background:green;}
100% { background:red; }
}
@-moz-keyframes blink {
0% { background:red; }
50% { background:green;}
100% { background:red; }
}
@-ms-keyframes blink {
0% { background:red; }
50% { background:green;}
100% { background:red; }
}
body{
-webkit-animation: blink 1s infinite;
-moz-animation: blink 1s infinite;
-ms-animation: blink 1s infinite;
}
If you expect the browser to support CSS animations, you can so something more interesting and perhaps less annoying. 如果您希望浏览器支持CSS动画,那么您可以更有趣,也许不那么讨厌。 Define in your style sheet: 在样式表中定义:
body {
-webkit-animation: changebg 1s infinite cubic-bezier(1,0,0,1);
-moz-animation: changebg 1s infinite cubic-bezier(1,0,0,1);
animation: changebg 1s infinite cubic-bezier(1,0,0,1);
}
@-moz-keyframes changebg {
0% {background-color: #f00;}
50% {background-color: #fff;}
100% {background-color: #f00;}
}
@-webkit-keyframes changebg {
0% {background-color: #f00;}
50% {background-color: #fff;}
100% {background-color: #f00;}
}
@keyframes changebg {
0% {background-color: #f00;}
50% {background-color: #fff;}
100% {background-color: #f00;}
}
And you're done, without JavaScript at all. 你完成了,没有JavaScript。 Unfortunately, CSS animations are not standard yet, so those hinge on prefixes, hence I had to repeat for -moz-
and -webkit-
. 遗憾的是,CSS动画尚未标准化,因此这些动画取决于前缀,因此我不得不重复使用-moz-
和-webkit-
。 It doesnt work on Opera and IE, for now. 目前它在Opera和IE上都不起作用。
x = 1;
assigns x
a value of 1, even in an if
statement. 即使在if
语句中,也为x
赋值1。 Use x == 1
in if
statements to keep the value of your variable unchanged. 在if
语句中使用x == 1
来保持变量的值不变。
For one thing, this: 首先,这个:
if (x = 1){
Should be this: 应该是这样的:
if(x == 1) {
Your statement sets x to 1, rather than tests it to see if it's 1. 你的语句将x设置为1,而不是测试它是否为1。
I would advice not to do this, since it might be pretty annoying, but this should work: 我建议不要这样做,因为它可能很烦人,但这应该工作:
var x = false;
function changecolors(){
var color=(x)?"green":"red"; // If X == true, then set to green, if false then blue
document.body.style.background = color; // Set color
x=!x; // Invert X
}
And then in the body: 然后在身体:
<body onload="setInterval(changecolors,1000)">
PS: Sorry if I'm not answering the question right...this code will change the background from blue to green every second repeatedly for an infinite amount of time. PS:对不起,如果我没有正确回答这个问题......这段代码会在无限长的时间内反复将背景从蓝色变为绿色。 (What I mean is that I kinda redid your code rather than explaining what was wrong with yours...) (我的意思是我有点重新编写你的代码而不是解释你的错误...)
You should definetly read some basic JavaScript tutorial or book. 您应该明确地阅读一些基本的JavaScript教程或书籍。 I am also new to JavaScript but some reading has helped. 我也是JavaScript新手,但有些阅读有所帮助。 Here http://www.w3schools.com/js/ you can find some good stuff as reference. 在这里http://www.w3schools.com/js/你可以找到一些好东西作为参考。
This should do the trick 这应该可以解决问题
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function change_color(flag){
var color = null;
if (flag === true){
var color = "red";
}else{
var color = "green";
}
document.body.style.background = color;
flag = !flag
var t=setTimeout(function(){change_color(flag)},1000);
}
</script>
</head>
<body onload="change_color(true)">
</body>
If you are going to manipulate the DOM a lot i recommend JQuery 如果你要操作DOM很多我推荐JQuery
I have created this function called toggle_colour for the very same purpose. 为了同样的目的,我创建了一个名为toggle_colour的函数。
function toggle_color(color1, color2, cycle_time, wait_time) {
setInterval(function first_color() {
document.body.style.backgroundColor = color1;
setTimeout(change_color, wait_time);
}, cycle_time);
function change_color() {
document.body.style.backgroundColor = color2;
}
}
Now you can simply copy the above code and call the function with two color codes. 现在您可以简单地复制上面的代码并使用两个颜色代码调用该函数。 Like, 喜欢,
toggle_color("#61beb3", "#90a2c6", 4000, 2000);
You can check the complete demo and more advanced toggle color functions in the article, Changing background color every X seconds in Javascript 您可以在文章中查看完整的演示和更高级的切换颜色函数, 在Javascript中每隔X秒更改背景颜色
Disclaimer: I am the author of this tutorial article. 免责声明:我是本教程文章的作者。
Your code is missing the closing </script>
tag and other issues mentioned above. 您的代码缺少结束</script>
标记和上面提到的其他问题。
Find below a fix of your code that removes the global variable. 在下面找到删除全局变量的代码修复。
<html>
<head>
<script type="text/javascript">
function changecolors() {
var t = setInterval('change()',1000);
}
function change() {
var color = document.body.style.background;
if(color == "red") {
document.body.style.background = "green";
} else {
document.body.style.background = "red";
}
}
</script>
</head>
<body onload="javascript:changecolors()">
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.