jQuery单循环一个图像循环

时间:2016-04-22 23:52:38

标签: javascript jquery

到目前为止,我有以下jQuery,我很陌生,我试图在透明框架内循环绘制22幅图像但在最后一帧上停止。我使用以下jQuery代码:

function swapImages(){
  var $active = jQuery('#frame-gallery .active');
  var $next = ($active.next().length > 0) ? $active.next() : jQuery('#frame-gallery img:first');
  $active.removeClass('active');
  $next.addClass('active');
}
jQuery(document).ready($startSwap = function(){
  // Run our swapImages() function every 5secs
  setInterval('swapImages()', 120);
});

我整天都在这里,为clearInterval尝试龋齿的地方,但它不起作用......

1 个答案:

答案 0 :(得分:1)

只需更改$next的逻辑 - 如果下一个节点存在,则只添加/删除类。如果下一个不存在,则清除间隔:



var interval;

function swapImages(){
  var $active = jQuery('#frame-gallery .active');
  
  if ($active.next().length > 0) {
    $active.removeClass('active');
    $active.next().addClass('active');
  } else {
    clearInterval(interval);
  }
}

jQuery(document).ready($startSwap = function(){
  // Run our swapImages() function every 5secs
  interval = setInterval(swapImages, 300);
});

.active { color: red; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="frame-gallery">
  <li class="active">a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
  <li>f</li>
  <li>g</li>
</ul>
&#13;
&#13;
&#13;