如何使用图像Carousel jQuery

时间:2015-09-13 15:39:47

标签: javascript jquery

我正在创建图片轮播

小提琴:https://jsfiddle.net/KyleKatarn/ojxy3o0g/4/

并且旋转木马中只有两个图像。现在我已创建变量AnimalClass { public: AnimalClass(); virtual void makeSound(){ printf("nosound";} } DogClass: public AnimalClass { public: DogClass(); void makeSound(){ printf("bufff";} } MasterClass { public: MasterClass(); AnimalClass *ani; void emitSound(){ani->makeSound();} } ChildAClass: public MasterClass { public: ChildAClass(){ani=new DogClass();} DogClass *ani; } main() { ChildAClass c; c.emitSound(); } ,当用户点击var current = 1控件按钮时,此变量获得next。现在我想要current++我希望变量if (current > 2)正常工作。但有一个问题我不想要我的变量current = 1。因为我只用了两张图片。我不会在我的图像轮播中看到黑色背景。我只想在检查第二张图片时,它会滚动回第一张图片

我的HTML

current = 3

我的JS

<div class="slider">
    <ul>
        <li><img src="http://dogfeathers.com/3d/povray/images/3DGDDDDC.GIF" alt="image" id="a"></li>
        <li><img src="http://www.doschdesign.com/images2/Red-DH-VASLA-1.jpg" alt="image"></li>
    </ul>
</div>
<div id="slider-nav">
    <button data-dir="prev">Previous</button>
    <button data-dir="next">Next</button>
</div>

1 个答案:

答案 0 :(得分:1)

animate语句后移动您的默认if操作或使用else

var imgLength = $('img').length;
var current = 1;
var currentImage = $('img');

$('button').on('click',function(){

    if($(this).data('dir') === 'next'){
        current++;
        if(current > imgLength){
            currentImage.animate({
                'left':'0px'
            });

            // return here:
            return current = 1;
        }

        // move default action behind if statement (or use ELSE)
        currentImage.animate({
            'left':'-=600px'
        });
    // add ELSE here, so that the next IF statement isn't checked unnecessarily:
    }else if($(this).data('dir') === 'prev'){
        current--;
        if(current < 1){
            currentImage.animate({
                'left': (600 * (1 - imgLength )) + 'px'
            });
            // return here:
            return current = imgLength;
        }

        // move default action behind if statement (or use ELSE)
        currentImage.animate({
            'left':'+=600px'
        });
    }
});

JSFiddle