0
我想創建一個pinterest效果,並通過wedding.reposition()設置div的位置。但是,我認爲outerHeight()函數不起作用,因爲它返回0px。我認爲這是由於圖像尚未加載,但我只在相關的div已被加載並附加到DOM(追加是同步的?)之後調用wedding.reposition()。使用outerHeight()與主幹的問題
有趣的是,如果幾秒鐘後通過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);
};
}
});
我似乎無法獲得加載函數的工作。例如'$(「img」)。load(function(){console.log(「test」) });'不跑? –
@丹塘需要更多的上下文來理解爲什麼。 – alex
嗨亞歷克斯,這就是我正在運行 - >即時試圖調用所有的圖像加載後,重新定位功能,但它似乎並沒有工作'$(document).ready(function(){ //獲取從服務器數據,初始化視圖 wedding.start(); $( 「IMG」)負載(函數(){ 的console.log( 「測試」) wedding.reposition(); }); });' –