开发者

jQuery fade in banner rotator issues

开发者_JAVA技巧

This seems so simple, but here I stand messing it up.

I'm trying to make a simple banner rotator (i know there are many plugins - i'm just trying to gain experience).

Problem #1. Currently, the first image does not fade out, only the second in. This is solved it I set fade to que after a timeout. I am suspicious that this is because the funciton is triggered before the pictures have loaded because I believe jQuery's onload is after the DOM is ready and does not wait for all pictures to be loaded. I proved myself wrong when i had the same results using document.onload

Problem #2. I can't repeat the function. I tried putting my function in a forever loop with

while(true) {
    setTimeout("fade()", 2500);
}

This fails entirely. I have little experience, and any points in any direction would be so helpful!

Code:

$.fn.preload = function() { //preload the picture
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

function nextImg() { //generate random image path
  var curImg = "images/";
  var randomNumber=Math.floor(Math.random()*11)
  curImg += randomNumber;
  curImg += ".jpg";
  $([curImg]).preload();
  return curImg;
}

function fade() {
  var img = nextImg(); //grab the random image path
    $("#umom1").fadeOut(1900, function() {
       $("#umom1").attr("src", img);
       $("#umom1").fadeIn(1900);
   });
}

$("document").ready( function() {
setTimeout("fade()", 2500);
});


You should call setInterval(fade, 2500).
The setInterval method will run a function every x milliseconds, unlike setTimeout, which only runs it once.

You should never pass a string to setInterval or setTimeout; instead, you should pass a function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜