简体   繁体   中英

Javascript slider add/remove function that doesn't remove first slide

I've looked at this site for a couple of years but only now have encountered a problem that couldn't be solved via reading the answers of others.

I feel like my problem is a simple one to overcome, but I'm having a block on it for some reason.

I have a 'slick' slider that adds and removes slides, in the future I hope to make it so that the first slide is an undeletable upload form. Each upload will then generate a new slide. Deleting that upload will remove that specific slide.

My first issue is that I'm not exactly sure how to make the first slide undeletable...If being hung up on this problem means I won't be able to tackle creating what I mentioned above, there may be cough cough paid work for someone who can pull it off. (Sorry if it's against the rules to say that)

Here is my code, hopefully it's all you need:

$(document).ready(function() {

  $('.add-remove').slick({
      dots: true,
      slidesToShow: 1,
      speed: 500,
      slidesToScroll: 1
  });
  var slideIndex = 1;
  $('.js-add-slide').on('click', function() {
      slideIndex++;
      $('.add-remove').slick('slickAdd','<div><h3>' + slideIndex + '</h3></div>');
  });

  $('.js-remove-slide').on('click', function() {
      $('.add-remove').slick('slickRemove', slideIndex - 1);
      if (slideIndex !== 0){
          slideIndex--;
      }
  });

});

What you call slideIndex is not the index, but the number of slides. This means you are always removing the last slide. slideCount would be a more suitable name. To restrict deletion and to just delete the active element you can do this:

var slideCount = 0, slideSequence = 0;

$('.js-remove-slide').on('click', function() {
    var slideIndex = $('.slick-slide.slick-active').data('slick-index');
    if (slideIndex != 0){
        $('.add-remove').slick('slickRemove', slideIndex);
        slideCount--;
    }
});

$('.js-add-slide').on('click', function() {
    slideCount++;
    $('.add-remove').slick('slickAdd','<div><h3>' + slideSequence + '</h3></div>');
    slideSequence++;
});

The add will add a new slide in the end probably, this depends on the implementation of slickAdd and it will always get the next number, even if something was deleted, to show where something was deleted and created.

In this case I would check for the length of slices and would only delete if the length is greater than 1.

Something like this should work

if ($(".slick-slide").length > 1) {
    // deletion code
}

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