jquery simple slideshow
I am trying to make a simple jquery slideshow, but I am not able to.
I am using the following code but I just get the second image not the first.
$(document).ready(function(){
$("#slides1").attr("src", "resources/images/slide_1.jpg");
$("#slides1").fadeOut(1000);
$("#slides1").delay(1000).attr("src", "resources/images/slide_2.jpg");
$("#slides1").fadeIn(1000).delay(1000);
}
);
What am I doing wrong?
slides is am img tag with id="slides1"
I tried the following code but still does not work.
$("#slides1").delay(500).attr("src", "resource开发者_JAVA技巧s/images/slide_2.jpg").delay(1000).fadeOut(1000).delay(1000).attr("src", "resources/images/slide_1.jpg").fadeIn(1000);
You are expecting to set the src
attr to slide_2.jpg
after a delay of 500, correct? If it is, what you are doing is wrong. You see .delay
works with the fxQueue
of jQuery which is a queue of functions that is used by affects, like fadeOut
etc., and does not affect calls like .attr
etc., that are not related to affects/animations. So you could pass a callback function to .fadeOut
and set the src
attribute in that, like so
$("#slides1")
.attr("src", "resources/images/slide_1.jpg") // show slide 1
.delay(500) // ...for 500ms
.fadeOut(1000, function () { // do fade out animation for 1000ms
$(this)
.attr("src", "resources/images/slide_2.jpg") // show slide 2
.fadeIn(1000) // ...by fading in for 1000ms
.delay(500) // ...for 500ms
});
Not tested, but should work. Tell me if this is not what you are trying to achieve.
Try this,
$(document).ready(function(){
$("#slides1").attr("src", "resources/images/slide_1.jpg");
$("#slides1").fadeOut(1000 ,
function (){
$("#slides1").delay(1000).attr("src", "resources/images/slide_2.jpg");
$("#slides1").fadeIn(1000).delay(1000);
}
);
}
);
You need to wait until the first image has loaded before executing the script, try...
$(window).load(function() {
$("#slides1").attr("src", "resources/images/slide_2.jpg").fadeOut(1000).delay(1000).attr("src", "resources/images/slide_1.jpg").fadeIn(1000);
});
EDIT: cleaned up and corrected code
The only way I've been able to create this behavior successfully is to chain two setTimeouts within a recursive function call.
$(document).ready(function(){
var images = ["resources/images/slide_1.png", "resources/images/slide_2.png"];
var time = 1000;
replace(0);
function replace(counter){
if( counter >= images.length)
counter = 0;
$("#slides1").attr("src",images[counter++]);
$("#slides1").fadeIn(time);
setTimeout(function(){
$("#slides1").fadeOut(time);
setTimeout(function(){
replace(counter);
}, time);
}, time);
}
});
精彩评论