2013-08-31 231 views
0

我使用Backbone渲染一個方形瓷磚元素,我在其中設置高度,然後動態設置寬度以匹配高度。但是,當試圖獲取元素高度時,我得到0返回。動態設置元素的高度和寬度

這裏是我的代碼:

var app = app || {}; 

app.ClassModelView = Backbone.View.extend({ 
    className: 'tile', 

    template: _.template('<%= name %>'), 

    render: function() { 
     var dim = 'calc(' + parseInt(100/app.global.rows) + '% - ' + app.global.margin * (app.global.rows + 1) + 'px)'; //e.g. "30% - 20px" 
     this.$el.append(this.template(this.model.attributes)).css({ 
      margin: app.global.margin + 'px', 
      height: dim, 
     }).css({ 
      width: this.$el.height() + 'px', 
     }); 

     return this; 
    } 
}) 

我將如何設置$el的高度寬度?我不確定是否我的語法錯誤,或者是使用Backbone的方式導致我的問題。

+1

您可以嘗試使用'.outerHeight(真)'代替。如果它不起作用,請考慮上傳代碼到http://www.jsfiddle.net向我們展示您的問題 – Itay

回答

1

我以前遇到類似的問題。在大多數情況下,這是因爲我的視圖已經呈現,但尚未插入到DOM中。處理嵌套視圖時這很常見。

你可以通過在你的onRender方法中設置一個斷點並檢查它來測試這個。$ el.parent()。你可能想要找幾個父母來確定父元素在DOM中。

您可以通過綁定到DOMNodeInserted事件解決這個問題:

this.$el.on('DOMNodeInserted', function(e) { console.log($(e.target).outerHeight()); }) 
相關問題