如何使用jquery循环幻灯片

时间:2012-12-15 10:25:13

标签: jquery

基本上我正在尝试使用jquery创建幻灯片。这里幻灯片导航工作正常但幻灯片循环不起作用。
我在这里尝试了 jsfiddle
我的剧本是:

 var currIndex = -1;

 function slideshow(slideshowId){
     var len=$("ul#"+slideshowId+" li.slides").length;
     currIndex = (currIndex + 1) % len;
     $("ul#"+slideshowId+" li.slides").hide();
     $("ul#"+slideshowId+" li.slide"+currIndex+"").fadeIn();     
 }

 function slidepagenation(slideshowId,slideno){    
        $("ul#"+slideshowId+" li.slides").hide();
        $("ul#"+slideshowId+" li.slide"+slideno+"").fadeIn();
        currIndex = slideno;
 }

var tshone = 0;
var tshtwo = 0;

    slideshow('slideshow-one');
    tshone =setInterval(slideshow('slideshow-one'), 500);
     slideshow('slideshow-two');
    tshtwo =setInterval(slideshow('slideshow-two'), 500);

    $('ul.slideshow-one li a').click(function(){
        clearInterval(tshone);
        var element = $(this);
        var slideshowid=element.parent().parent().attr('class');
        var slideno = $("ul.slideshow-one li a").index($(this));
        slidepagenation(slideshowid,slideno); 
    });

    $('ul.slideshow-two li a').click(function(){
        clearInterval(tshtwo);
        var element = $(this);
        var slideshowid=element.parent().parent().attr('class');
        var slideno = $("ul.slideshow-two li a").index($(this));
        slidepagenation(slideshowid,slideno); 
    });

我的HTML在这里:

<ul class="slideshow" id="slideshow-one">
    <li class="slides slide0" style="display:block">
    Slide one
    </li>
    <li class="slides slide1">
    Slide two
    </li>
    <li class="slides slide2">
    Slide three
    </li>     
</ul>
<div class="full-length clearfix txt-center">
<ul class="slideshow-one">
    <li><a>1</a></li>
    <li><a>2</a></li> 
    <li><a>3</a></li>     
</ul>
</div>
<br><br>
<ul class="slideshow" id="slideshow-two">
    <li class="slides slide0" style="display:block">
    Slide one
    </li>
    <li class="slides slide1">
    Slide two
    </li>    
</ul>
<div class="full-length clearfix txt-center">
<ul class="slideshow-two">
    <li><a>1</a></li>
    <li><a>2</a></li>    
</ul>
</div>

1 个答案:

答案 0 :(得分:1)

setInterval接受函数在该时间间隔内运行,但您要给它undefined

tshone =setInterval(slideshow('slideshow-one'), 500);

...因为该行调用 slideshow并将其返回值传递给setInterval。由于slideshow未返回值,因此调用它的结果为undefined

相反:

tshone =setInterval(function() {
    slideshow('slideshow-one');
}, 500);

现在我们正在创建一个函数并将其传递给setInterval。该函数每半秒调用slideshow

另请注意,您只使用一个 currIndex,但您尝试将其用于两个不同的幻灯片。那不行。我建议完全删除currIndex,并从DOM中找出哪个幻灯片处于活动状态。像这样:

function slideshow(slideshowId){
    var slideShow = $("ul#"+slideshowId);
    var slide;

    slide = slideShow.find("li.slides:visible");
    if (slide.length > 1) {
        slide.hide();
        slide = $();
    }
    slide = slide.hide().nextAll("li.slides").first();
    if (slide.length == 0) {
        slide = slideShow.find("li.slides").first();
    }
    slide.fadeIn();
}