jQuery简单无限循环滑块逻辑

时间:2018-12-27 18:03:33

标签: jquery slider logic infinite-scroll jquery-ui-slider

我是Jquery的新手,他制作了一个简单的静态滑块,其中包含五个具有相同类名(.sl_thumb)的图像 这是下一个和上一个锚点上的代码- 右锚(.right_nav_link),左锚(.left_nav_link) 幻灯片(.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 :(得分:0)

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