2015-11-30 42 views
0

我有一些RGB顏色的像這樣的列表:如何在jQuery中每X秒更改一次div背景顏色而無效?

var ls = ['rgb(255,0,0)','rgb(0,255,0)', 'rgb(0,0,255)'];

而且我想更新一個div背景顏色使用的顏色從列表中每2秒。爲了實現這一目標,我寫了下面的代碼:

(function($){ 
    var $box = $('#box'); 
    var temp; 

    var ls = ['rgb(255,0,0)','rgb(0,255,0)', 'rgb(0,0,255)']; 

    $.each(ls, function(i, x){ 
    temp = setInterval(change(x), 2000); 
    }); 

    function change(color) { 
    $box.css('background-color', color); 
    } 

})(jQuery); 

我的目標是在移動到下一種顏色之前顯示在列表中2秒每一種顏色,但是這個代碼等待2秒鐘,然後執行循環,所以我只能看到最後一種顏色是藍色(rgb(0,0,255))。

我的HTML看起來像這樣:

<html> 
<head> 
    <title>bin</title> 
    <style> 
    #box{ 
     width: 200px; 
     height: 200px; 
     background-color: rgb(0,0,0); 
    } 
    </style> 
</head> 

<body> 

    <div id="box"></div> 
    <script src="https://code.jquery.com/jquery-1.11.3.js"></script> 
    <script src="main.js"></script> 
</body> 
</html> 

謝謝大家。

+0

你可以用'setInterval' – Rajesh

+1

參見本:http://jsfiddle.net/7h7dv25j/1/ – Rayon

+1

感謝@Rayon Dabre,我很喜歡你的解決方案,謝謝。 –

回答

1

我發現使用keyframes實現使用純CSS這個顏色過渡一個更好的方式,雖然這種技術不受IE9和支持下,但我認爲這如果有人在閱讀,值得在這裏添加。

<!DOCTYPE html> 
<html> 
<head> 
<style> 
div { 
    width: 100px; 
    height: 100px; 
    background-color: red; 
    -webkit-animation-name: example; /* Chrome, Safari, Opera */ 
    -webkit-animation-duration: 4s; /* Chrome, Safari, Opera */ 
    animation-name: example; 
    animation-duration: 4s; 
} 

/* Chrome, Safari, Opera */ 
@-webkit-keyframes example { 
    0% {background-color: red;} 
    25% {background-color: yellow;} 
    50% {background-color: blue;} 
    100% {background-color: green;} 
} 

/* Standard syntax */ 
@keyframes example { 
    0% {background-color: red;} 
    25% {background-color: yellow;} 
    50% {background-color: blue;} 
    100% {background-color: green;} 
} 
</style> 
</head> 
<body> 

<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p> 

<div></div> 

</body> 
</html> 

這裏是一個DEMO

1

您在setInterval之前執行change,而應該添加匿名函數並在裏面調用您的change函數。

$.each(ls, function(i, x){ 
    temp = setInterval(function() { change(x); }, 2000); 
    }); 
+0

這將改變所有的顏色在同一時間,所以有與原來相同的問題:http://jsfiddle.net/cng5zb6h/ –

3

這一切都歸結到某個地方保存迭代狀態。例如像這樣:

function Cycle(array) { 
    var i = 0; 
    this.next = function() { 
     i %= array.length; 
     return array[i++]; 
    } 
} 

var colors = new Cycle(['rgb(255,0,0)','rgb(0,255,0)', 'rgb(0,0,255)']); 

$('#box').css('background-color', colors.next()); 

setInterval(function() { 
    $('#box').css('background-color', colors.next()) 
}, 2000);