2

我或多或少是 Jquery 的初学者,从它开始,我尝试制作一个可点击的循环幻灯片,基于这个。到现在为止还挺好。该代码有效(见下文)。我的问题:

  1. 没有更简单的方法来编写代码。我有点为 prev 和 next 重复相同的代码。

  2. 当我单击下一个/上一个链接并开始动画时 - 在动画期间我再次单击时,有时图像会闪烁或出现错误。有没有办法强制动画在我的点击做出反应之前完成。

Javascript:

    $(function() {

    $('#prev').click(function() {
        var $active = $('#slideshow IMG.active');
        var $prev = $active.prev();
        $active.addClass('last-active');

    if($active.is(":first-child")){$prev = $("IMG:last-child");}
        $prev.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 1000, function() {
                $active.removeClass('active last-active');
            }); 

    }); 


    $('#next').click(function() {
        var $active = $('#slideshow IMG.active');
        var $next = $active.next();
        $active.addClass('last-active');

    if($active.is(":last-child")){$next = $("IMG:first-child");}
        $next.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 1000, function() {
                $active.removeClass('active last-active');
            }); 

    }); 

    });

CSS:

    #slideshow {position:relative; height:350px; opacity:1.0;}
    #slideshow IMG {position:absolute; top:0; left:0; z-index:8; opacity:0.0;}
    #slideshow IMG.active {z-index:10; opacity:1.0;}
    #slideshow IMG.last-active {z-index:9;}
    #next {color:#0000ff; cursor:pointer;}
    #prev {color:#0000ff; cursor:pointer;}

HTML:

    <div id="slideshow">
        <img src="image1.jpg" class="active" />
        <img src="image2.jpg" />
        <img src="image3.jpg" />
        <img src="image4.jpg" />
    </div>
    <div id="next">NEXT</div>
    <div id="prev">PREV</div>
4

2 回答 2

1

好吧,每次我遇到构建一些循环东西的需要时,我都会使用jQuery Cycle PlugIn。这可能不是您优化问题的答案,但我认为每个人都应该看看 Cycle 插件。

正如您在演示页面上看到的那样,您也可以非常轻松地使用下一个/上一个按钮。就像

$('#slideshow').cycle({ 
    fx:     'fade', 
    speed:  'fast', 
    timeout: 0, 
    next:   '#next', 
    prev:   '#prev' 
});

您的 HTML 代码可以保持这种状态。

于 2012-04-21T14:43:00.923 回答
0

http://jsfiddle.net/kPD4n/

你去吧。

1)为“NEXT”和“PREV”按钮添加相同的类,然后检查哪个被单击。
2) 添加 .stop(0,1) 跳转到动画结尾。

不过还是有点小毛病...

于 2012-04-21T14:48:15.147 回答