1

我需要<div>每 2 秒加载带有随机图像的 PHP 文件,并带有淡入淡出效果,所以我使用 javascript 和 jQuery。我编写函数来隐藏 div,加载文件,而不是显示它并等待 2 秒,然后它应该再次调用函数,但它只发生了一次然后它停止了。

这是功能:

function random(){
   $("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php").animate({opacity: '1.0'}).delay(2000, function(){
   random();
});
random();
4

3 回答 3

4

做这个:

(function random(){
  var timer;
  $("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php", function(){
     $(this).animate({opacity: '1'});
     timer = setTimeout(random, 2000);
  });
})();

在这里,我们创建自调用函数并在内部调用它,setTimeout以便在图像加载和动画部分完成后一次又一次地调用它。加载所有图像后,您需要调用clearTimeout(timer)停止运行。setTimeout

于 2012-06-30T20:09:30.460 回答
1

请求完成setTimeout(random, 2000);后尝试添加:load

function random(){
  var rndImg = $("#randomImage1");
  rndImg.fadeOut().load("../images/randomImage.php",function(){
      rndImg.fadeIn();
      setTimeout(random, 2000);
  });
};
random()
于 2012-06-30T20:12:24.003 回答
-4

The problem you have is that you're trying to use .delay() as a replacement for the native setTimeout(), which isn't what it's intended to do. The .delay() function is designed to add a pause between jQuery animation effects, not to delay the execution of another function, and doesn't accept a callback function. See the jQuery documentation for the .delay() function.

As has already been covered in previous answers, you can use the native setInterval() function to implement the delay you're after:

function random(){
    $("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php").animate({opacity: '1.0'});
    setInterval(random, 2000);
}
random();

Note that this will animate the #randomImage1 element back to full opacity, and set the interval to call the function again, even if the AJAX call from .load() didn't return a success response. If that's not what you want, you can instead move that code into an anonymous function passed as the success callback on .load(), like so:

function random(){
    $("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php", 
    function() {
        $("#randomImage1").animate({opacity: '1.0'});
        setInterval(random, 2000) 
    });
}
random();
于 2012-06-30T20:20:13.750 回答