jQuery 单循环图像循环

jQuery single looping an image cycle

本文关键字:循环 图像 单循环 jQuery      更新时间:2023-09-26

到目前为止,我有以下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);
});

我整天都在这样做,尝试龋齿的地方清除间隔,但它行不通......

只需稍微更改$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>