2012-10-24 35 views
2

我在div中添加了一個div元素,並希望使用masonry來排列這些內部元素。除非我在setTimeout回調函數中初始化砌體,否則,石匠會中斷。jQuery Masonry在追加容器後不能立即工作

// I have a `#media` div in my html 
var outerDiv = $('<div>').attr('style', 'width: 720px;'); 
this.$('#media').append(div); 

// I create lots of boxes in a boxes div 
var boxes = $('<div>').append(
    $('<div>').attr('style', 'width: 160px; height: 180px; margin: 10px 0px; ' + 
     'background-color: red; float: left;').addClass('item'), 
    $('<div>').attr('style', 'width: 340px; height: 120px; margin: 10px 0px; ' + 
     'background-color: red; float: left;').addClass('item'), 
    $('<div>').attr('style', 'width: 160px; height: 120px; margin: 10px 0px; ' + 
     'background-color: red; float: left;').addClass('item'), 
    $('<div>').attr('style', 'width: 160px; height: 180px; margin: 10px 0px; ' + 
     'background-color: red; float: left;').addClass('item'), 
    $('<div>').attr('style', 'width: 340px; height: 100px; margin: 10px 0px; ' + 
     'background-color: red; float: left;').addClass('item'), 
    $('<div>').attr('style', 'width: 340px; height: 160px; margin: 10px 0px; ' + 
     'background-color: red; float: left;').addClass('item'), 
    $('<div>').attr('style', 'width: 160px; height: 180px; margin: 10px 0px; ' + 
     'background-color: red; float: left;').addClass('item'), 
    $('<div>').attr('style', 'width: 160px; height: 120px; margin: 10px 0px; ' + 
     'background-color: red; float: left;').addClass('item') 
); 

outerDiv.append(boxes); 

// without the setTimeout wrapper, this breaks (in Chrome, everything clusters 
// in the top left; in Firefox, everything lines up in a column on the left) 
setTimeout(function() { 
    boxes.masonry({ 
    itemSelector: '.item', 
    columnWidth: 180, 
    isResizable: true, 
    }); 
}); 

想法?

+0

如果你閱讀砌體文檔,那麼你可以找到附加的方法。 http://masonry.desandro.com/docs/methods.html – undefined

+0

附加的方法是有用的,當你有一個容器裏面已經masonried框,然後你添加額外的元素。這不是問題:在最初的砌體設置期間,錯誤顯示出來。 – tenedor

回答

1

您是否在砌體文檔中選中了「卸載介質並重疊」?另請參閱this discussion以及開發人員的提示。您的問題也顯示沒有Ajax加載和其他加載器,它通常是內容不及時到達,因爲它是非常重的數據。

砌體需要每個div(圖像,文本或視頻)中的內容來計算所有的div尺寸 - 在可以首次計算佈局之前。如果您正在加載帶有圖像的圖像,或者圖像非常大或類似,則砌體沒有尺寸(從內容)開始工作,並會顯示這種典型的「錯誤」。這就是爲什麼你的

setTimeout(function() { 
    boxes.masonry({ 
    itemSelector: '.item', 
    columnWidth: 180, 
    isResizable: true, 
}); 

在這種情況下工作,因爲足夠的時間內容加載/附加/出現/被構建。