嘗試這樣:
jQuery(document).ready(function($) {
var CollManag = (function() {
var $ctCollContainer = $('#grid'),
collCnt = 1,
init = function() {
changeColCnt();
initEvents();
initPlugins();
},
changeColCnt = function() {
var w_w = $(window).width();
if(w_w <= 480) n = 1;
else if(w_w <= 700) n = 2;
else n = 3;
},
initEvents = function() {
$(window).on('smartresize.CollManag', function(event) {
changeColCnt();
});
},
initPlugins = function() {
$ctCollContainer.imagesLoaded(function(){
$ctCollContainer.masonry({
itemSelector : '.box_item',
columnWidth : function(containerWidth) {
return containerWidth/n;
},
isAnimated : true,
animationOptions: {
duration: 400
}
});
});
};
return { init: init };
})();
CollManag.init();
});
或者
$(window).load(function()
{
var columns = 3,
setColumns = function() { columns = $(window).width() > 700 ? 3 : $(window).width() > 480 ? 2 : 1 };
setColumns();
$(window).resize(setColumns);
$('#grid').masonry(
{
itemSelector: '.box_item',
gutterWidth: 0,
isAnimated: true,
columnWidth: function(containerWidth) { return containerWidth/columns; }
});
});