Masonry 不会以百分比形式居中元素。为此,我尝试使用以下解决方法并且效果很好:
var $container;
jQuery(document).ready(function() {
// The following functions are used to allow us to center an itee list
// (aligned with the Masonry library) that uses percentage values for list items width
window.Isotope.prototype._getMasonryGutterColumns = function() {
var gutter = this.options.masonry.gutterWidth || 0;
containerWidth = this.element.parent().width();
this.masonry.columnWidth = this.options && this.options.masonry.columnWidth
|| this.$filteredAtoms.outerWidth(true)
|| containerWidth;
this.masonry.columnWidth += gutter;
this.masonry.cols = Math.floor((containerWidth + gutter) / this.masonry.columnWidth);
this.masonry.cols = Math.max(this.masonry.cols, 1);
};
window.Isotope.prototype._masonryReset = function() {
this.masonry = {};
this._getMasonryGutterColumns();
var i = this.masonry.cols;
this.masonry.colYs = [];
while (i--) { this.masonry.colYs.push( 0 ); }
};
window.Isotope.prototype._masonryResizeChanged = function() {
var prevColCount = this.masonry.cols;
this._getMasonryGutterColumns();
return ( this.masonry.cols !== prevColCount );
};
window.Isotope.prototype._masonryGetContainerSize = function() {
var gutter = this.options.masonry.gutterWidth || 0;
var unusedCols = 0,
i = this.masonry.cols;
while ( --i ) {
if ( this.masonry.colYs[i] !== 0 ) {
break;
}
unusedCols++;
}
return {
height : Math.max.apply( Math, this.masonry.colYs ),
width : ((this.masonry.cols - unusedCols) * this.masonry.columnWidth) - gutter
};
};
// The item list container
$container = jQuery('.item').parent();
// Initialize Masonry
$container.imagesLoaded(function() {
$container.isotope({
masonry: {
itemSelector: '.item',
transitionDuration: '.3s'
/* Insert your options */
}
});
// Bind event listener
$container.isotope('on', 'layoutComplete', onLayout);
onLayout();
});
});
var timeout;
/**
* This callback is called on 'layoutComplete' event
*/
function onLayout() {
// To prevent to call this function too much times,
// we need to use a timeout
if (timeout != undefined) clearTimeout(timeout);
timeout = setTimeout("centerItems()", 200);
}
/**
* Center the list items
*/
function centerItems(callback) {
// The reordering has to be repeated for each items list
jQuery.each(jQuery('.item').parent(), function(key, container) {
var items = jQuery(container).children();
// Looking for the rightest item
var maxRightIndex = 0;
for (var i = 1; i < items.length; i++) {
if (jQuery(items[i]).offset().left > jQuery(items[maxRightIndex]).offset().left) {
maxRightIndex = i;
}
}
var leftMargin = jQuery(items[0]).offset().left - jQuery(container).offset().left;
var rightMargin = jQuery(container).offset().left + jQuery(container).width() - (jQuery(items[maxRightIndex]).offset().left + jQuery(items[maxRightIndex]).width());
var left = (rightMargin - leftMargin) / 2;
jQuery(container).css('width', 'auto').animate({left: left});
})
}
以及以下css规则
html, body {
overflow-x: hidden;
}
注意:您还需要包含同位素库 ( http://isotope.metafizzy.co/ )