2012-12-13 139 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) }); 
     }); 
    } 
});