jQuery动画制作幻灯片图像循环在同一个方向上迭代

jQuery animate - making slideshow image loop iterately in the same direction

本文关键字:同一个 方向 迭代 循环 动画制作 幻灯片 图像 jQuery      更新时间:2023-09-26

我想用jQuery制作自己的幻灯片。在这里,我被滑块图像的方向卡住了。我希望它只循环一个方向(从右到左)。请参阅下面的代码:

HTML:

<div class="flash-banner">
    <ul>
       <li>
          <img src="img/flash-banner.jpg" alt="Black glass banner " />
       </li>
       <li>
          <img src="img/flash-banner-contact.jpg" alt="Black glass banner " />
       </li>
       <li>
          <img src="img/flash-banner-our-work.jpg" alt="Black glass banner " />
       </li>
    </ul>
</div>

JavaScript:

$(document).ready( function ( e ) {
    slideshow( 6000 );
});
function slideshow( speed ) {
    // Get width from image
    $pic = $('.flash-banner ul li img')[0];
    $width = $pic.width;
    // Count the total number of children of UL 
    $count = $('.flash-banner ul').children().length;
    // Set width to UL  
    var $ul = $width * $count;
    $('.flash-banner ul').css('width', $ul);
    var i = 1;
    setInterval( function ( e ) {
        if ( i > $count - 1 ) {
              // I think the problem is here, but I can't fix it
           i = 0;
           var b = 0;
        } else {
           var b = $width * i;
        }
        console.log( b );
        $element = $('.flash-banner ul');
        $element.animate(
           {'margin-left': -b },
           { duration: speed },
           { delay: speed }
        );
        i++;
    }, speed );
}

我还在http://jsfiddle.net/FzDtD/1/

使用clearInterval()停止动画,而不是将i重置为0。

如果要重新循环动画,请调用.stop()停止它,修复css将横幅移回原始位置,然后再次调用动画函数。

jsfiddle此处

或者,您可以尝试停止动画并将所有值重置为初始状态,但我发现这有时会变得很混乱,因为您需要手动确保重置所有变量才能正常工作。