如何使用setInterval函数更改幻灯片?

时间:2019-01-30 16:40:21

标签: javascript jquery html css

到目前为止,这是我的JS代码。现在,我可以单击滑块上的每个按钮,它将更改为相应的幻灯片。

$('.slide-nav').on('click', function(e) {
e.preventDefault();
// get current slide
var current = $('.flex--active').data('slide'),
  // get button data-slide
  next = $(this).data('slide');
console.log(current);
$('.slide-nav').removeClass('active');
$(this).addClass('active');

if (current === next) {
  return false;
} else {
  $('.slider__wrapper').find('.flex__container[data-slide=' + next + ']').addClass('flex--preStart');
  $('.flex--active').addClass('animate--end');
  setTimeout(function() {
    $('.flex--preStart').removeClass('animate--start flex--preStart').addClass('flex--active');
    $('.animate--end').addClass('animate--start').removeClass('animate--end flex--active');
   }, 900);
  }
 });

我正在使用的滑块看起来像这样,可以看到html / css https://codepen.io/mikun/pen/YWgqEX

因此,除了单击以更改幻灯片之外,我还想滚动以更改幻灯片

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式模拟点击功能:

setInterval(function () {
  $(".slide-nav.active").next().click();
}, 1000);

您需要检查这是否是最后一个并尝试:

setInterval(function () {
  if ($(".slide-nav.active").next().length > 0)
    $(".slide-nav.active").next().click();
  else
    $(".slide-nav").first().click();
}, 1000);

演示:https://codepen.io/anon/pen/ZwBVzo