1

我有以下 jQuery:

            var $active = $('#slideshow li.active');

            if ( $active.length == 0 ) $active = $('#slideshow li:last');

            // use this to pull the images in the order they appear in the markup
            var $next =  $active.next().length ? $active.next()
                : $('#slideshow li:first');

            // uncomment the 3 lines below to pull the images in random order

            // var $sibs  = $active.siblings();
            // var rndNum = Math.floor(Math.random() * $sibs.length );
            // var $next  = $( $sibs[ rndNum ] );


            $active.addClass('last-active');

            $next.css({opacity: 0.0})
                .addClass('active')
                .animate({opacity: 1.0}, 500, function() {
                    $active.removeClass('active last-active');
                });

如何修改它以便我可以向后循环?

我已经走了这么远,但它不会从第一个元素循环回到最后一个元素。一定有一些我想念的相当简单的东西,但我真的无法理解它。

            var $active = $('#slideshow li.active');

            if ( $active.length == 0 ){ $active = $('#slideshow li:last');}

            // use this to pull the images in the order they appear in the markup
            var $next =  0 ? $active.prev()
                : $('#slideshow li:first');

            // uncomment the 3 lines below to pull the images in random order

            // var $sibs  = $active.siblings();
            // var rndNum = Math.floor(Math.random() * $sibs.length );
            // var $next  = $( $sibs[ rndNum ] );


            $active.addClass('last-active');

            $next.css({opacity: 0.0})
                .addClass('active')
                .animate({opacity: 1.0}, 500, function() {
                    $active.removeClass('active last-active');
                });
4

1 回答 1

1

当前解决方案检查元素之后是否有active元素。我们将更改它以查看元素之前是否有一个。active最初的后备是选择#slideshow. 我们将改为选择最后一个。

var $next = $active.prev().length ? $active.prev() : $('#slideshow li:last');

如果您不熟悉三元运算符,它本质上与编写 if 语句相同:

// If there are previous elements
if ( $active.prev().length > 0 ) {
    // The next element will be the previous element
    $next = $active.prev();
} else {
    // The next element will be the last list item in #slideshow
    $next = $("#slideshow li:last");
}
于 2012-05-28T16:19:08.853 回答