如何获取主干视图中的尺寸(高度/宽度)信息?
在我的主干应用程序的渲染功能中,我想用空行填充表格的其余部分以实现交替行外观,但我不知道要添加多少行。我尝试了 this.el.clientHeight
、$(this.el).height()
以及此类函数的所有其他排列,让它们全部返回 0。有谁知道怎么办?我也不想添加太多以免引入滚动条。
var bar = Backbone.View.extend({
initialize: function(){
_.bindAll(this, "render");
},
render: function(){
var html = "<h1>Hi!</h1>";
$(this.el).html(html);
var myWidth = this.el.width();
alert(myWidth);
return this;
}
});
var foo = Backbone.View.extend({
el: $('#myElement'),
initialize: function(){
_.bindAll(this, "render");
this.subview = new bar();
},
render: function(){
$(this.el).append(this.subview.render().el);
return this;
}
});
对于那些遇到与我相同问题的人的解决方案:您必须等待元素完全附加到 dom 才能获取高度/宽度信息。为了解决这个问题,我在渲染完全完成后添加了一个渲染后调用,该调用返回并处理任何小细节。
In the render function of my backbone app, I want to fill the rest of the table with empty rows for the alternating row look, but I dont know how many rows to add. I tried this.el.clientHeight
, $(this.el).height()
, and all other permutations of such functions to have them all return 0. Does anyone know how to do this? I also dont want to add too many in order not to introduce a scroll bar.
var bar = Backbone.View.extend({
initialize: function(){
_.bindAll(this, "render");
},
render: function(){
var html = "<h1>Hi!</h1>";
$(this.el).html(html);
var myWidth = this.el.width();
alert(myWidth);
return this;
}
});
var foo = Backbone.View.extend({
el: $('#myElement'),
initialize: function(){
_.bindAll(this, "render");
this.subview = new bar();
},
render: function(){
$(this.el).append(this.subview.render().el);
return this;
}
});
Solution for those stuck with the same problem as I had: You have to wait for the elements to be fully attached to the dom in order to get height/width info. In order to resolve this I added a postrender call after the render is fully done which went back and handled any small details.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在某些浏览器上,宽度和高度信息在设置 html 后不会立即可用。原因是你已经更新了 DOM,但浏览器可能还没有布局新页面。
在过去,我采用将调用推迟一个时间点的方式,以便浏览器有时间在您测量之前赶上。您可以使用
underscore.defer()
来实现此目的。例如:此外,jQuery.width() 可能会为您提供比 clientWidth 更好的兼容性。祝你好运!
On some browsers, the width and height information will not be immediately available right after setting the html. The reason for this is that you have updated the DOM, but the browser may not have laid out the new page yet.
In the past I have resorted to deferring the call by a tick so that the browser has time to catch up before you measure it. You can use
underscore.defer()
for this. For example:Also, jQuery.width() will probably give you better compatibility than clientWidth. Good luck!
尝试在附加它后获取高度(因此在“foo”而不是“bar”中)。
例如在“foo”中
Try getting the height after you attach it, (so in "foo" as opposed to "bar").
For example in "foo"
你的观点应该是这样的:
希望有帮助
Your view should look something like this:
Hope that helps