Simple JQuery Timed Image Rotation
For some reason, the following has no effect. This is most likely a product of me not having any sleep and the solution is probably very simple...
JS:
<script src="http://code.jquery.com/jquery-1.6.1.js"> </script>
<script>
function swapImages(){
var $active = $('#switch .active');
var $next = ($('#switch .active').next().length > 0) ? $('#switch .active').next() : $('#switch img:first');
$active.fadeOut(function(){
$active.removeClass('active');
$next.fadeIn().addClass('active');
});
}
$(document).ready(function(){
// Run our swapImages() function every 5secs
setInterval('swapImages()', 5000);
}
</script>
HTML:
<div id="switch"><img src="images开发者_运维知识库/chalk.jpg" class="active" /><img src="images/students.jpg" /></div>
CSS:
#switch{
margin-left: auto;
margin-right: auto;
width: 996px;
height: 374px;
}
#switch img{
display:none;
}
#switch img.active{
display:block;
}
I created a Fiddle, it works fine for me.
The only thing I have changed (besides adding colors for presentation purposes) is I have changed your setInterval
call to this:
setInterval(swapImages, 5000);
Generally, it is not a good practice to pass a string to setInterval
. It works like eval
, which we all know is evil :). Pass a function to it. If you really want to do more, use a closure (which is unnecessary here).
there's a plugin for that ;)
http://jquery.malsup.com/cycle/lite/
it's really light weight, and gives some nice options for the animation to switch the images.
You are missing );
at the end of document.ready
function, and change the setTnterval
to the actual function.
$(document).ready(function(){
// Run our swapImages() function every 5secs
setInterval(swapImages, 1000);
});
Working example: http://jsfiddle.net/niklasvh/4d6X5/
精彩评论