2013-08-31 141 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()); }) 
相关问题