函数结束时,Jquery重复设置inteval

时间:2018-05-16 02:18:09

标签: javascript jquery setinterval

在这个脚本中,我希望按编号0,1,2显示图像并每次重复,问题是下一个图像显示,直到动画和过渡图像结束。

var n_img_s = 2;
i = 0;

function more_slider() {
  if (i > n_img_s) {
    i = 0;
  }
  jQuery(".img_" + i).show(3000).delay(3000);
  jQuery(".img_" + i).hide(2000).delay(1500);
  i++;
}

setInterval("more_slider()", 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="slider_cover">
  <img src="https://images.pexels.com/photos/6602/food-plate-woman-hand.jpg?auto=compress&cs=tinysrgb&h=350" style="display:none;" class="img_0" />
  <img src="https://images.pexels.com/photos/6602/food-plate-woman-hand.jpg?auto=compress&cs=tinysrgb&h=350" style="display:none;" class="img_1" />
</div>

例如,我需要显示图像0,隐藏完成并在此时显示下一张图像,但直到完成另一张图像。

但我不知道如何整合setInterval

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

//get all the images
var $images = $('#slider_cover img');

//accept in the next image index to show
function more_slider(nextImageIndex) {
  //get the image you should show, using eq()
  //so the element will still be in a jQuery object
  var $nextImage = $images.eq(nextImageIndex);
  
  //show the image, and then do something after the duration ends
  $nextImage.show(3000, function(){
    //hide the image, and then do something after the duration ends
    $nextImage.hide(2000, function(){
      //pass in the incremented index, performing a modulus
      //on it so that if the length is equal to the number
      //of images it will go back to 0
      more_slider(++nextImageIndex % $images.length);
    });
  });
}

//initialize the loop, giving it the first image index to show
more_slider(0);
.img_0 { border: 2px solid red; }
.img_1 { border: 2px solid blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="slider_cover">
  <img src="https://images.pexels.com/photos/6602/food-plate-woman-hand.jpg?auto=compress&cs=tinysrgb&h=350" style="display:none;" class="img_0" />
  <img src="https://images.pexels.com/photos/6602/food-plate-woman-hand.jpg?auto=compress&cs=tinysrgb&h=350" style="display:none;" class="img_1" />
</div>