How do I get JQuery Masonry to recognize added ite

2019-04-30 09:02发布

This is the same question as this one, but I have a repro of the issue on JSFiddle up here. So I thought I'd repost.

JQuery Masonry seems to only assess the children of its container once, on first run. After that, it's impossible to get it to look at the DOM again to get it to reassess its children.

4条回答
贪生不怕死
2楼-- · 2019-04-30 09:19

if you are using jQuery, this will solve all your problems.

You are including Masonry in your html/php page with something like this:

<script src="js/masonry.min.js"></script>
<script>
    $('#ms-container').masonry({
        columnWidth: '.ms-item',
        itemSelector: '.ms-item'
    });
</script>

Instead, leave it like this:

<script src="js/masonry.min.js"></script>
<script src="js/masonry-init.js"></script>

And create the js/masonry-init.js file with the following:

$('#ms-container').masonry({
    columnWidth: '.ms-item',
    itemSelector: '.ms-item'
});
var masonryUpdate = function() {
    setTimeout(function() {
        $('#ms-container').masonry();
    }, 500);
}
$(document).on('click', masonryUpdate);
$(document).ajaxComplete(masonryUpdate);

Never worry about it again!

查看更多
等我变得足够好
3楼-- · 2019-04-30 09:30

I seem to have solved this by adding a line to reload the "bricks" to the _reLayout function in the JQuery Masonry code at line 305.

_reLayout : function( callback ) {

  // This is my added line. 
  // Items might have been added to the DOM since we laid out last.
    this.reloadItems();

  // reset columns
  var i = this.cols;
  this.colYs = [];
  while (i--) {
    this.colYs.push( this.offset.y );
  }
  // apply layout logic to all bricks
  this.layout( this.$bricks, callback );
},

// ====================== Convenience methods ======================

// goes through all children again and gets bricks in proper order
reloadItems : function() {
  this.$bricks = this._getBricks( this.element.children() );
},


reload : function( callback ) {
  this.reloadItems();
  this._init( callback );
},

Anyone see any problem with this?

查看更多
倾城 Initia
4楼-- · 2019-04-30 09:33

You have to pass the new content to Masonry's appended method:

$("#container").append(content).masonry("appended", content);

I updated your fiddle here.

查看更多
SAY GOODBYE
5楼-- · 2019-04-30 09:39

I made use of the reload method:

.masonry( 'reload' )

Here's the masonry doc for reload:

"Convenience method for triggering reloadItems then .masonry(). Useful for prepending or inserting items."

查看更多
登录 后发表回答