jQuery 每秒更改 css 颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8527536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:38:43  来源:igfitidea点击:

Changing the css color every second

jquerycss

提问by Ricardo

Possible Duplicate:
How to loop a css background image with Jquery every few seconds?

可能的重复:
如何每隔几秒用 Jquery 循环一个 css 背景图像?

I'm wondering how to achieve a simple "animation" effect of colors changing every second and if there is a way to animate the animation it can be even better.

我想知道如何实现颜色每秒变化的简单“动画”效果,如果有一种方法可以为动画制作动画效果会更好。

I have just tried something like:

我刚刚尝试过类似的事情:

$('.box').delay(1000).css("background","red");

And it doesn't work at all (the delay function isn't working).. anyways i need like two of them:

它根本不起作用(延迟功能不起作用)。无论如何,我需要其中两个:

$('.box').delay(1000).css("background","red");
$('.box').delay(1000).css("background","green");

So that it becomes red -> wait a second and becomes green -> becomes red again..

所以它变成红色 - >稍等片刻然后变成绿色 - >再次变成红色..

Is it possible? thanks!

是否可以?谢谢!

回答by Damen TheSifter

$(document).ready(function() {
    setInterval(function() {
        $('body').animate( { backgroundColor: 'red' }, 300)
            .animate( { backgroundColor: 'green' }, 300);
    }, 1000);
});

http://jsfiddle.net/theSifter/yR6jc/

http://jsfiddle.net/theSifter/yR6jc/

回答by danludwig

setInterval(function() {
    var box = $('.box');
    if (box.css('background-color') == 'red') {
        box.css({'background-color':'green'});
    }
    else {
        box.css({'background-color':'red'});
    }
}, 1000);

回答by Chris Fulstow

<h1 id="ho">Ho ho ho!</h1>
<h2 id="mc">Merry Christmas!</h2>

<script>
    var flag = false;
    setInterval(function() {
        flag = !flag;
        $("#ho").css("background", flag ? "red" : "green");
        $("#mc").css("background", flag ? "green" : "red");
    }, 1000);
</script>

回答by Leto

I think you have to use the javascript setInterval method :

我认为您必须使用 javascript setInterval 方法:

See here: http://www.w3schools.com/jsref/met_win_setinterval.asp

见这里:http: //www.w3schools.com/jsref/met_win_setinterval.asp

so:

所以:

setInterval(function() {
// Code to execute every second
}, 1000);