【问题标题】:jQuery slider - prev and next issuejQuery 滑块 - 上一期和下一期
【发布时间】:2014-03-03 16:55:31
【问题描述】:

我正在尝试使用 prev 和 next 按钮制作一个简单的滑块。 如果向前迈出一步而不是向后迈出一步,我并不总是得到以前的图像。 我注意到下一个和上一个按钮不使用相同的索引,但我不知道如何解决。

   $("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>

【问题讨论】:

标签: jquery slider


【解决方案1】:

只需修改一点 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/

【讨论】:

  • 我正在尝试更好地理解 JQuery,但我惊讶地发现将图像包装在您的示例中的锚标记仍然有效。但看起来代码只是在图像中循环,为什么/如何循环每个图像周围的链接?
【解决方案2】:

这是一种方法:

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/

【讨论】:

  • 谢谢,你成就了我的一天!
  • @user3371372 欢迎您,请通过单击我的答案左侧的白色小复选标记将此答案标记为已接受。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多