按钮点击播放淡入/淡出滑块

时间:2014-03-26 10:00:51

标签: javascript jquery html css slider

我创建了一个fadein / Fadeout滑块。它正在寻找汽车。我想点击下一个/上一个按钮来播放滑块。

HTML

<section class="wrapper">
<ul class="slider">
    <li><img src="http://www.tylershields.com/images/gallery/art_gallery.jpg" alt="" /></li>
    <li><img src="http://www.goa-tourism.com/images/photogallery/1287634889_pid_kala%20academy%20art%20gallery.jpg" alt="" /></li>
    <li><img src="http://www.magnoliabakery.com/uploads/GalleryImageModel/105/filemask/mag1003_magnolia_fall_14original.gallery.jpg" alt="" /></li>
    <li><img src="http://www.lancasterconventioncenter.com/_images/_gallery/gallery15.jpg" alt="" /></li>
</ul>
<button data-dir="prev">Prev</button>
<button data-dir="next">Next</button>
</section>

CSS

*               {margin:0; padding:0;}
.wrapper        {width:800px; margin:0 auto; max-width:100%;}
.slider         {position:relative;}
.slider li      {position:absolute; top:0; left:0; list-style:none; width:100%; opacity:0;}
.slider li img              {width:100%;}
.slider li:first-child      {position:relative; display:block; opacity:1;}

脚本

var current = 0,
    elem    = $('.slider li'),
    slides  = $('.slider li').length,
    speed   = 3000,
    transSpeed = 1000;

function autoSlide(){

    current = (current == (slides-1)) ? 0 : +1;

    $('.slider').find('li')
        .filter(':eq('+ current +')').addClass('current').animate({'opacity':1}, transSpeed)
        .siblings('li').removeClass('current').animate({'opacity':0}, transSpeed);
    };

var timer = setInterval(autoSlide, speed);

$('button').on('click', function(){
    clearInterval(timer);
     autoSlide();
     timer =setInterval(autoSlide, speed);
});

Fiddle Demo

1 个答案:

答案 0 :(得分:2)

你的问题在这一行:

current = (current == (slides-1)) ? 0 : current + 1 // you were doing +1 which will always return 1

您的current变量始终设置为1

希望这会有所帮助!

Fiddle Demo


<强>更新

要移动上一个和下一个,您需要检查单击哪个按钮,因为您只使用一个处理程序,请参阅下面的代码:

您可以点击autoSlidefunction(element)

的元素

完整代码

function autoSlide(element) {
    var clicked = $(element).text().toLowerCase().trim(); // Get next or prev
    if (clicked == "next")
        current = (current == (slides - 1)) ? 0 : current + 1; // Current will be incremented
    else
        current = (current == 0) ? 0 : current - 1; // decrease in current
    $('.slider').find('li')
        .filter(':eq(' + current + ')').addClass('current').animate({
            'opacity': 1
        }, transSpeed)
        .siblings('li').removeClass('current').animate({
            'opacity': 0
        }, transSpeed);
};

var timer = setInterval(autoSlide, speed);

$('button').on('click', function () {
    clearInterval(timer);
    autoSlide($(this)); // to get clicked element to autoSlide()
    timer = setInterval(autoSlide, speed);
});

Updated Fiddle