解决简单的JavaScript幻灯片问题

时间:2014-12-21 17:27:05

标签: javascript jquery

我有一个问题,我的幻灯片在5张幻灯片中的第2张后被卡住,理想情况下,我想循环播放幻灯片,我想知道是否有人可以帮助解决它。代码如下:

slideshow.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/slideshow.css">
    <title>CS98SI Homework 1 - Slideshow</title>
</head>
<body>
    <h1>Slideshow</h1>
    <div class="slideshow">
        <img src="img/kitten_1.jpg">
        <img src="img/kitten_2.jpg">
        <img src="img/kitten_3.jpg">
        <img src="img/kitten_4.jpg">
        <img src="img/kitten_5.jpg">
    </div>
    <script src="js/jquery-1.9.1.min.js"></script>
    <script src="js/slideshow.js"></script>
</body>
</html>

slideshow.js

var createSlideshow = function(slideshowElem, duration) {
    // TODO: Implement createSlideshow.
    if(!duration){
        duration = 5000;
    }
    slideshowElem.children('img').hide();
    var i = 1;
    var anchor = slideshowElem.children('img').first();
    anchor.fadeIn();

    function fades(n){
        anchor.fadeOut('slow',function(){
            $(this).next().fadeIn('slow');
        });
        anchor = anchor.next();
    }
    setInterval(fades(i),duration);
};

$(document).ready(function() {
    // TODO: Use createSlideshow to create a slideshow on the page.
    createSlideshow($('.slideshow'),500000);
});

要点可以在这里找到:https://gist.github.com/anonymous/f8bf16b1eae0c434e84a

非常感谢!

1 个答案:

答案 0 :(得分:1)

http://jsbin.com/jesisa/1/edit

function createSlideshow(slideshowElem, duration) {

  $(slideshowElem).each(function(){
    var pause = duration||5000;
    var img = $(this).find('img'); // all of them!
    var n = img.length;     // how many images we have
    var i = 0;

    img.css({position:"absolute"}).hide(); // hide all but first one (index 0)

    function fades(){
        img.delay(pause).fadeOut(800).eq(i++%n).stop().fadeIn(800, fades);
    }
    fades();
  });

}

$(document).ready(function() {
    createSlideshow('.slideshow', 3000);
});