Как остановить бесконечную прокрутку после загрузки контента

Я создал бесконечную прокрутку, которая генерирует новый набор изображений, когда доходит до конца документа. Я хочу, чтобы эта бесконечная прокрутка показывала изображения на разной высоте, но я хочу, чтобы она останавливалась после загрузки всех изображений. Вот кодеин: https://codepen.io/MakaylaElizabeth/pen/QWLYqRp

Вот часть JS:

function GenerateItems(){
    var items = '';
    for(var i=0; i < Imgs1.length; i++){
      items += '<div class="grid-item c'+(2)+'" ><img src="'+Imgs1[i%Imgs1.length]+'" /></div>';  
      }
      for(var i=0; i < Imgs2.length; i++){
      items += '<div class="grid-item c'+(1)+'" ><img src="'+Imgs2[i%Imgs2.length]+'" /></div>'; 
      }
      for(var i=0; i < Imgs3.length; i++){
      items += '<div class="grid-item c'+(0)+'" ><img src="'+Imgs3[i%Imgs3.length]+'" /></div>'; 
      }
    return $(items); 
  }

/*SimpleInfiniteScroll */
  function Infinite(e){
    if((e.type == 'scroll') || e.type == 'click'){
      var doc = document.documentElement;
      var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
      var bottom = top + $(window).height();
      var docBottom = $(document).height();

      if(bottom + 10 >= docBottom){
        $grid.revealItems(GenerateItems());
      }
    }
  }


  $grid.revealItems(GenerateItems());

  $(document).on('click','.filter-item',function(){
    $('.filter-item.active').removeClass('active');
    $(this).addClass('active');
    var f = $(this).data('f');
    console.log(f);
    $grid.find('.grid-item');
    $grid.isotope({filter: f});
  });


   $(window).scroll(Infinite);  
})

Я пытался сломать функцию создания элементов после каждого цикла for и не имел результатов. Пожалуйста, дайте мне знать, если я могу предоставить дополнительную информацию. Спасибо.


person Elizabeth    schedule 22.09.2019    source источник


Ответы (1)


В вашей функции Infinite отмените привязку события прокрутки, когда у вас больше нет элементов.
В вашей функции GenerateItems см. мои комментарии в шагах.

var Imgs1 = [
  "https://tympanus.net/Development/GridLoadingEffects/images/1.jpg",
  "https://tympanus.net/Development/GridLoadingEffects/images/1.jpg",
  "https://tympanus.net/Development/GridLoadingEffects/images/1.jpg",
  "https://tympanus.net/Development/GridLoadingEffects/images/1.jpg",
  "https://tympanus.net/Development/GridLoadingEffects/images/1.jpg",
  "https://tympanus.net/Development/GridLoadingEffects/images/1.jpg"
];

var Imgs2 = [
  "https://tympanus.net/Development/GridLoadingEffects/images/8.jpg",
  "https://tympanus.net/Development/GridLoadingEffects/images/8.jpg",
  "https://tympanus.net/Development/GridLoadingEffects/images/8.jpg",
  "https://tympanus.net/Development/GridLoadingEffects/images/8.jpg",
  "https://tympanus.net/Development/GridLoadingEffects/images/8.jpg",
  "https://tympanus.net/Development/GridLoadingEffects/images/8.jpg"
];

var Imgs3 = [
  "https://tympanus.net/Development/GridLoadingEffects/images/12.png",
  "https://tympanus.net/Development/GridLoadingEffects/images/12.png",
  "https://tympanus.net/Development/GridLoadingEffects/images/12.png",
  "https://tympanus.net/Development/GridLoadingEffects/images/12.png",
  "https://tympanus.net/Development/GridLoadingEffects/images/12.png",
  "https://tympanus.net/Development/GridLoadingEffects/images/12.png",
  "https://tympanus.net/Development/GridLoadingEffects/images/12.png",
  "https://tympanus.net/Development/GridLoadingEffects/images/12.png"
];

$(document).ready(function() {
  $grid = $(".filterGallery");

  $.fn.revealItems = function($items) {
    var iso = this.data("isotope");
    var itemSelector = iso.options.itemSelector;
    $items.hide();
    $(this).append($items);
    $items.imagesLoaded().progress(function(imgLoad, image) {
      var $item = $(image.img).parents(itemSelector);
      $item.show();
      iso.appended($item);
    });

    return this;
  };

  $grid.isotope({
    masonry: {
      gutter: 20,
      fitWidth: true,
      columnWidth: 300
    },
    itemSelector: ".grid-item",
    filter: "*",
    transitionDuration: "0.4s"
  });

  $grid.imagesLoaded().progress(function() {
    $grid.isotope();
  });
  
  /* Array Loop */

  function GenerateItems(max) {
    var items = [];
    var img_src;
    // while there are items in Imgs1 remove the first one 
    while (img_src = Imgs1.shift()) {
      // and push it into items
      items.push('<div class="grid-item c' + 2 + '" ><img src="' + img_src + '" /></div>');
      // if we have the max number of items stop and return them
      if (items.length === max) return $(items.join(""));
    }    
    // after Imgs1 is emptied start collecting from Imgs2
    while (img_src = Imgs2.shift()) {
      items.push('<div class="grid-item c' + 1 + '" ><img src="' + img_src + '" /></div>');
      if (items.length === max) return $(items.join(""));
    }
    while (img_src = Imgs3.shift()) {
      items.push('<div class="grid-item c' + 0 + '" ><img src="' + img_src + '" /></div>');
      if (items.length === max) return $(items.join(""));
    }
    // if we make it to here all 3 arrays have been emptied, and we have less than the max
    // return what there is
    return $(items.join(""));
  }

  /* SimpleInfiniteScroll */
  function Infinite(e) {
    if (e.type == "scroll" || e.type == "click") {
      var doc = document.documentElement;
      var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
      var bottom = top + $(window).height();
      var docBottom = $(document).height();

      if (bottom + 10 >= docBottom) {
        // pass the max number of items to generte
        let items = GenerateItems(8);
        if (items.length == 0) {
          // out of items
          $(window).off("scroll", Infinite);
        } else {
          $grid.revealItems(items);
        }
      }
    }
  }

  /* Filter on Click */
  $grid.revealItems(GenerateItems(8));

  $(document).on("click", ".filter-item", function() {
    $(".filter-item.active").removeClass("active");
    $(this).addClass("active");
    var f = $(this).data("f");
    console.log(f);
    $grid.find(".grid-item");
    $grid.isotope({ filter: f });
  });

  $(window).scroll(Infinite);
});
body {
  margin: 0;
  padding: 0;
  width: 100%;
}

/* Gallery */
#gallery .filterGallery{
  width: 100%;
  margin: 20px auto !important;
}

.grid-item{
  width: 300px;
  padding: 20px;
}

#gallery img{
  display: block;
  position: relative;
  max-width: 100%;
}

.filterList li{
  cursor: pointer;
  display: inline-block;
  padding: 10px 12px 10px 12px;
}

.filterList li:hover{
  color: #000;
}

.filterList li.active{
  color: #000;
}

.filterList{
  background: #9F9C99;
  color: #fff;
  height: 40px;
  padding: 0;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/2.2.0/isotope.pkgd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/3.1.8/imagesloaded.pkgd.min.js"></script>

<body>

<!-- Filter -->
<div class="filterList">
	<ul>
		<li data-f="*" class="filter-item active">All</li>
		<li data-f=".c0" class="filter-item">Section 1</li>
		<li data-f=".c1" class="filter-item">Section 2</li>
		<li data-f=".c2" class="filter-item">Section 3</li>
	</ul>	
</div>
  
<!-- Gallery Section (GS) -->
<div id="gallery">
<div class="filterGallery">
</div>
</div>  

</body>

person Arleigh Hix    schedule 22.09.2019
comment
Спасибо за ответ. Я сделал codepen, потому что я не смог заставить это работать, потому что моя функция GenerateItems снова и снова добавляет все изображения. Он не уменьшится и не достигнет 0. знаете, как я могу загрузить эти массивы в функцию, чтобы это работало? Я хочу иметь возможность показывать 8 фотографий одновременно. - person Elizabeth; 24.09.2019
comment
@Elizabeth Теперь это должно делать то, что ты хочешь. - person Arleigh Hix; 24.09.2019
comment
Спасибо @Arleigh за вашу помощь, я некоторое время пытался решить эту проблему с кодом. Мне нужно разбить цикл while, когда пользователь нажимает на раздел. Потому что прямо сейчас фотографии загружаются в порядке цикла while, а разделы 1 и 2 не будут отображать фотографии, пока вы не прокрутите страницу, чтобы загрузить больше для раздела 3. Я обновил codepen, чтобы попытаться исправить это. Я использовал оператор continue со ссылкой на глобальную переменную, который не работает. Можете ли вы посоветовать, как это исправить? Спасибо. - person Elizabeth; 13.10.2019