How can I use Masonry multiple times per page with the same class name?

十年热恋 提交于 2019-12-12 15:15:41

问题


I need to have multiple Masonry grids per page. I'm generating the code with a wordpress loop, so every div container has the same class name.

Is there a way to call Masonry on all div containers with the same name?

html

 <!--Masonry 1-->
<div class="print-slider">
    <div class="print-slider-sizer"></div>
    <div class="gutter-sizer"></div>
    <div class="print-slider-item"></div>
    <div class="print-slider-item"></div>
    <div class="print-slider-item"></div>
    <div class="print-slider-item"></div>
</div>

<!--Masonry 2-->
<div class="print-slider">
    <div class="print-slider-sizer"></div>
    <div class="gutter-sizer"></div>
    <div class="print-slider-item"></div>
    <div class="print-slider-item"></div>
    <div class="print-slider-item"></div>
    <div class="print-slider-item"></div>
</div>

JS

var grid = document.querySelector('.print-slider');
var msnry;

imagesLoaded( grid, function() {
  // init Isotope after all images have loaded
  msnry = new Masonry( grid, {
    itemSelector: '.print-slider-item',
    columnWidth: '.print-slider-sizer',
    gutter: '.gutter-sizer',
    percentPosition: true,
  });
});

Here is a code pen for the problem:

http://codepen.io/anon/pen/OXBrPb

Thanks for your help!


回答1:


With document.querySelector('.print-slider') you only get the first html element that has the print-slider class. That's why only the first masonry is initialized.

Below is your code adjusted a bit in order to catch all .print-slider elements and init the masonries respectively. The difference is that I get the elements by class name and then loop through them. I used body as the selector for the imagesLoaded because I didn't have the whole html structure. I would suggest that you wrap the masonries in one div and use that one for checking whether the images are loaded. Or, even better, do the check for each masonry separately, before doing the initialization inside the foreach.

var elements = document.getElementsByClassName('print-slider');
var msnry;

imagesLoaded( document.querySelector('body'), function() {
  // init Isotope after all images have loaded
  var n = elements.length;
  for(var i = 0; i < n; i++){
    msnry = new Masonry( elements[i], {
      itemSelector: '.print-slider-item',
      columnWidth: '.print-slider-sizer',
      gutter: '.gutter-sizer',
      percentPosition: true,
    });
  }
});


来源:https://stackoverflow.com/questions/38765659/how-can-i-use-masonry-multiple-times-per-page-with-the-same-class-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!