ピンタレストのようなエフェクトを作成し、wedding.reposition() で div の位置を設定しようとしています。ただし、outerHeight() 関数は 0px を返すため、機能していないと思います。これは画像がまだ読み込まれていないためだと思いましたが、関連する div が読み込まれて DOM に追加された後にのみ wedding.reposition() を呼び出します (追加は同期ですか?)。
興味深いことに、setTimeout 関数を使用して数秒後に wedding.reposition を実行すると、機能します。誰かがこれに対する解決策を持っているかどうか疑問に思っていますか?
//repositions all the elements on the page
wedding.reposition = function() {
var $post = $(".post");
//sets col position classes
for(var i = 0, len = $post.length; i < len; i++) {
//starts from base 1 rather than base 0
var colClass = "col" + (i % 4 + 1);
$post.eq(i).addClass(colClass);
//implies it is on the second or greater row
if(i >= 4) {
var $col = $("." + colClass);
//gets row of the element in the current column
var row = Math.floor(i / 4);
var $prev = $col.eq(row - 1);
//determines the height of the current object
console.log($prev.outerHeight());
var currentObjectHeight = $prev.position().top + $prev.outerHeight() + 15;
$col.eq(row).css("top", currentObjectHeight);
}
};
};
//PostsView corresponds to the overall view holding individual PostView
wedding.views.PostsView = Backbone.View.extend({
el: "#column-container",
initialize: function(){
_.bindAll(this);
this.collection.on("reset", this.render);
this.collection.fetch();
},
render: function(){
this.collection.each(function(model) {
this.initializePostView(model);
}, this);
wedding.reposition();
},
initializePostView: function(model) {
var html = new wedding.views.PostView({model: model});
this.$el.append(html.render().el);
}
});
wedding.views.PostView = Backbone.View.extend({
className: "post",
template: "#post-template",
initialize: function(options) {
_.bindAll(this);
this.template = _.template($(this.template).html());
},
render: function() {
this.preload();
return this;
},
preload: function() {
var image = new Image();
var that = this;
image.src = this.model.get("src");
image.onload = function() {
var html = that.template( {model: that.model.toJSON() });
that.$el.append(html);
};
}
});