簡體   English   中英

jQuery滑塊-上一個和下一個問題

[英]jQuery slider - prev and next issue

我正在嘗試使用上一個和下一個按鈕制作一個簡單的滑塊。 如果向前走而不是向后走,我不會總是得到前一張圖片。 我注意到下一個和上一個按鈕沒有使用相同的索引,但是我不知道該如何解決。

   $("img").hide();
    $("img").first().show();

    var currentItem = $("img").first().next().index();
    var lastItem = $("img").last().index();


    $('#next').click(function(){
        $("img").hide();
        $("img").eq(currentItem).show();
        if(currentItem == lastItem){
            currentItem = 0;
        }else{
            currentItem = $("img").eq(currentItem).next().index();
        }
    });


   var currentItem2 = $("img").last().prev().index();

    $('#prev').click(function(){
        $("img").hide();
        $("img").eq(currentItem2).show();
        if( currentItem2 == lastItem ){
            currentItem2 = 2;
        }else{
            currentItem2 = $("img").eq(currentItem2).prev().index();

        }
    });

這是我的html代碼

 <div id="slider">

    <img src="bilder/walle.jpg" alt=""/>
    <img src="bilder/up.jpg" alt=""/>
    <img src="bilder/toystory.jpg" alt=""/>
    <img src="bilder/nemo.jpg"alt=""/>

    <div id="next">Next</div>
    <div id="prev">prev</div>
</div>

只需修改一下Trevor的代碼,您就可以得到以下內容:

var images = [];
$('#slider img').each(function () {
    images.push($(this));
    $(this).hide();
});

var imgcount = images.length;
var currentItem = 0;
images[currentItem].show();

$('#next').click(function () {
    images[currentItem].hide();
    currentItem = (currentItem + 1) % imgcount;
    images[currentItem].show();
});

$('#prev').click(function () {
    images[currentItem].hide();
    if (currentItem > 0)
        currentItem--;
    else
        currentItem = imgcount - 1;
    images[currentItem].show();
});

然后,如果您要添加新圖像,您的代碼仍然有效,並且每次單擊下一個或上一個時,您都不會隱藏網頁中的所有圖像:)

http://jsfiddle.net/wmxzK/4/

這是一種實現方法:

var images = [];
$('#slider img').each(function(){
    images.push($(this));    
});
var imgcount = images.length;
$("img").hide();
$("img").first().show();
var currentItem = 0;

$('#next').click(function(){
        $("img").hide();
        currentItem++;
        images[currentItem%4].show();        
});

$('#prev').click(function(){
        $("img").hide();
       currentItem--;
       if(currentItem < 0)
           currentItem = imgcount-1;
       images[currentItem%4].show();
});

小提琴:

http://jsfiddle.net/wmxzK/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM