2012-12-13 67 views
0

有誰知道我在做什麼錯?jQuery自動刷新div發生故障

基本上,我在將內容(圖像)加載到div標記後,每隔x秒刷新一次。所以這就是我想出來的,並且它很好用,直到它將文件恢復到它進行手動刷新爲止。

當前過程如下所示:

加載...淡出,淡入&然後消失,重新出現幾秒鐘後。

什麼應該發生如下:

加載...淡出,淡入...淡出,淡入...(你的想法,循環)

代碼:

$(document).ready(function() { 
    $("#webcam").load("image.html").fadeIn("slow"); 
    var refreshId = setInterval(function() { 
     $("#webcam_img").fadeOut("slow"); 
     $("#webcam").load('image.html'); 
     $("#webcam_img").fadeIn("slow"); 
    }, 5000); 
}); 

在線文件可以在這裏找到:http://colourednoise.co.uk/scripts/webcam.htm

謝謝

回答

3

load是異步的。您正在對一個元素調用fadeIn,然後將其替換爲load。在load的回調中您需要fadeIn以確保元素存在。

$("#webcam").load('image.html', function(){ 
    $("#webcam_img").fadeIn("slow"); 
}); 
+0

哈..我甚至沒有注意到.. +1 –

+0

再次看了它之後,答案是真實的ly是我的答案和@ wirey's的組合。您可能會在圖像淡出之前將其替換(並以有線方式記下),然後在加載元素之前淡入圖像。 –

+0

謝謝你們兩位!作品完美:-) –

3

嘗試移動你的淡入對於淡出的回調函數內,因此等待,直到淡出完成第一

$("#webcam_img").fadeOut("slow",function(){ 
     $("#webcam").load('image.html'); 
     $("#webcam_img").fadeIn("slow"); 
    }); 

下面是完整的例子

$(document).ready(function() { 
    $("#webcam").load("image.html").fadeIn("slow"); 
    var refreshId = setInterval(function() { 
     $("#webcam_img").fadeOut("slow",function(){ // <-- added callback function 
     $("#webcam").load('image.html'); // now this 
     $("#webcam_img").fadeIn("slow"); // and this waits for fadeOut to complete first 
     }); 
    }, 5000); 
}); 
+0

要做到這一點,我將不得不刪除AR refreshId = setInterval的( function(){would not I?因此停止刷新自己的'autoness' –

+0

@JamesLawson不,你不..我剛剛更新了我的答案,告訴你它是如何看起來像 –

+0

這裏也是一個例子,你可以看到http://jsfiddle.net/fX3fG/相同的概念.. –

1

這裏有一個稍微不同的方式做到這一點,以確保在下一次刷新被排隊等待每個圖像滿載:

$(document).ready(function() { 
    $("#webcam").load("image.html").fadeIn("slow", function() { setTimeout(refreshImage, 5000) }); 

    function refreshImage() { 
     $("#webcam_img").fadeOut("slow",function(){ 
      $("#webcam").load('image.html'); 
      $("#webcam_img").fadeIn("slow", function() { setTimeout(appendDateToBody, 5000) }); 
     }); 
    } 
});