JQuery函数循环

Ten*_*ous 0 jquery loops function

我试图让它成为我的网站背景每隔几秒随机改变颜色.我可以让它改为随机颜色,但我如何让它循环?

<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>
Run Code Online (Sandbox Code Playgroud)

Aln*_*tak 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);
} 
Run Code Online (Sandbox Code Playgroud)

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

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

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

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