How do I get JQuery Masonry to recognize added items?

随声附和 提交于 2019-12-07 05:04:43

问题


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.


回答1:


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

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

I updated your fiddle here.




回答2:


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?




回答3:


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."




回答4:


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!



来源:https://stackoverflow.com/questions/7853779/how-do-i-get-jquery-masonry-to-recognize-added-items

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