简体   繁体   中英

How to change slides using setInterval function?

This is my JS code so far. Right now I can click on each button on the slider and it will change to the corresponding slide.

$('.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);
  }
 });

the slider I am working with looks like this one to see the html/css https://codepen.io/mikun/pen/YWgqEX

So in addition to clicking to change slides I would like to scroll to change slides

You can simulate the click function this way:

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

You need to check if this is the last and try this:

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

Demo: https://codepen.io/anon/pen/ZwBVzo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM