JQuery函数循环

时间:2013-01-17 21:41:54

标签: jquery function loops

我试图让它变成我的网站背景每隔几秒随机变化一次。我可以把它改成随机颜色,但是如何让它循环?

<script type="text/javascript">
$(document).ready(function() {

    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';  

    function colourSet(){
       $("body").animate({ backgroundColor: hue}, 2000);
    }   

    colourSet();

});
</script>

3 个答案:

答案 0 :(得分:5)

只需将函数寄存器本身作为自己的完成处理程序,就可以使其循环:

function colourSet() {
   var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; 
   $("body").animate({ backgroundColor: hue}, 2000, colourSet);
} 

注意:必须在功能内拾取色调,否则每次都会保持相同颜色。

只是为了好玩,你也可以使用一些Javascript hacks(ahem)使色调代码略微缩短:

function r() { return ~~(256 * Math.random()) };
function colourSet() {
   var hue = 'rgb(' + [r(), r(), r()] + ')';
   $("body").animate({ backgroundColor: hue}, 2000, colourSet);
}  

利用按位~(“not”)运算符的两种用法将浮点数转换为整数,并且因为将数组连接到字符串会自动在数组上执行.toString() - 导致以逗号分隔的列表。

答案 1 :(得分:3)

尝试使用setInterval。见下文,

$(document).ready(function() {

    setInterval(function () {
       var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';  
       colourSet(hue);
    }, 30000); //30 seconds

    function colourSet(hue){
       $("body").animate({ backgroundColor: hue}, 2000);
    }   
});

答案 2 :(得分:1)

使用setInterval功能

<script type="text/javascript">
$(document).ready(function() {

    setInterval(function(){
        var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';  

        function colourSet(){
           $("body").animate({ backgroundColor: hue}, 2000);
        }   

        colourSet();
    },60000 /* 60 seconds */);
});
</script>