-->

jQuery masonry with Wordpress and imagesLoaded

2019-04-14 20:04发布

问题:

I am using jquery masonry on a wordpress theme I am working on. After struggling with getting it to work for a while I found that this:

        <script type="text/javascript">
        jQuery(function () { 
          jQuery('#masonry-wrap').masonry({ 
           itemSelector: '.masonry-box', 
           columnWidth: 283 
          }); 
        })
        </script>

Seems to be working fine for me... However checking the site in Chrome and Safari pushes the bottom of the containing elements into the following elements...

Now I read somewhere, that this can be solved by using the imagesLoaded plugin and the code for that I found here: http://masonry.desandro.com/demos/images.html - however since I am absolutely terrible with jQuery, I'm having a little difficulty getting it to work.

Could anyone help me incorporate it into the code I am already using and that works (the one above)?

Any help would be greatly appreciated!! Julian

回答1:

I think this should work for you;

// Masonry Trigger
var $container = jQuery('#masonry-wrap');

$container.imagesLoaded( function(){
   $container.masonry({ 
     itemSelector: '.masonry-box', 
     columnWidth: 283 
   }); 
})

Remember to use the latest version of imagesLoaded, I had a problem a while back and the reason was my version was slightly out of date.

EDIT

That said, I only use imagesLoaded when I've loaded in new content via AJAX and am using the reLayout method. If you run masonry on $window.load() after the images are loaded it should run fine too.

(function($){

    $(window).load(function() {

      // Masonry Trigger
      var $container = $('#masonry-wrap');

      $container.masonry({
         // options
         itemSelector: '.masonry-box', 
         columnWidth: 283 
      });

    }); 

})(jQuery);