JQuery простой бесконечный цикл логики слайдера - PullRequest
0 голосов
/ 27 декабря 2018

Я новичок в Jquery и делаю простой статический слайдер с пятью изображениями с одинаковым именем класса (.sl_thumb). Это код для следующей и предыдущей привязки - привязка справа (.right_nav_link), привязка слева (.left_nav_link) MainDiv of slide (.slide_container)

Мои предыдущие и следующие ссылки работают нормально, но когда слайдер достигает последнего слайда, он останавливается, я пытаюсь сделать слайдер с бесконечным циклом, чтобы он снова достигал первого слайда послепрошлой.Как новичок, я перепробовал много вещей, но смутился, какую логику я могу использовать.

$(document).ready(function () {
    var src = 'img/img1.jpg';
    $(".right_nav_link").click(function () {
        var next = false;
        $($("img").filter(".sl_thumb")).each(function (key, value) {
            if ($(this).attr('src') == src) {
                next = true;
            } else if (next) {
                next = false;
                src = $(this).attr('src');
                $(".slide_container").css('background-image', 'url(' + src + ')');
                return;
            }
        });
    });
$(".left_nav_link").click(function () {
        var prev = false;
        $($("img").filter(".sl_thumb").get().reverse()).each(function (key, value) {
            // console.log(key,value);
            if ($(this).attr('src') == src) {   
                prev = true;
            } else if (prev) {
                prev = false;
                src = $(this).attr('src');
                $(".slide_container").css('background-image', 'url(' + src + ')');
                return;
            }
        });
    });
});

1 Ответ

0 голосов
/ 27 декабря 2018

$( document ).ready(function() {
  var src = 'img/img1.jpg';
  
  function adjustSlideContainer ( adjustPositionAmount ) {
    //get all the images
    var $thumbnails = $( 'img.sl_thumb' );
    //find the current one shown
    var $current = $thumbnails.filter( '[src="'+ src +'"]' );
    //get its index
    var currentIndex = $thumbnails.index( $current );
    //adjust the index to the image that should be shown next
    var nextIndex = currentIndex + adjustPositionAmount;
    
    if ( nextIndex < 0 ) {
      //if it's before the first one, wrap to the last one
      nextIndex = $thumbnails.length - 1;
    } else if ( nextIndex >= $thumbnails.length ) {
      //if it's after the end one, wrap to the first one
      nextIndex = 0;
    }
    
    src = $thumbnails.eq( nextIndex ).attr( 'src' );
    $( '.slide_container' ).css( 'background-image', 'url(' + src + ')' );
  }
  
  $(".right_nav_link").click(function() {
    //go to the next image
    adjustSlideContainer( 1 );
  });
  
  $(".left_nav_link").click(function() {
    //go to the previous image
    adjustSlideContainer( -1 );
  });
});
...