简体   繁体   English

在IE中将其设置为自动后获取div的高度

[英]Getting the height of a div after setting it to auto in IE

I'm writing some JavaScript that changes the size of some content. 我正在写一些JavaScript,它可以更改某些内容的大小。 To do this I need to know the size of a div within my content. 为此,我需要知道内容中的div大小。 If I have the following html: 如果我有以下html:

<div id="wrapper">
   ... other stuff ...
   <div id="inner" style="height:400px">Some text in here</div>
   ... other stuff ...
</div>

And the following JavaScript: 以及以下JavaScript:

$('#inner').height('auto');
var height = $("#wrapper").height();

In FireFox and Chrome the height variable increases as the inner div expands to fit all the text. 在FireFox和Chrome中,高度变量随着内部div扩展以适合所有文本而增加。 In IE this stays the same. 在IE中,它保持不变。 I guess it doesn't redraw the div straight away. 我猜它不会立即重绘div。 Anybody know how to get the new correct height in IE? 有人知道如何在IE中获得新的正确高度吗?

Cheers 干杯

问题在于该元素不会立即重绘,因此您需要异步测量高度-设置一个0毫秒的超时值来测量它并继续执行。

Try it this way: 尝试这种方式:

$(function() {
  $('#inner').height('auto');
  var height = $("#wrapper").height();
});

Wrapping it in $(function() { }); 将其包装在$(function() { }); makes it wait for the DOM to render before running the script. 使它在运行脚本之前等待DOM呈现。 It's probably a good idea to put anything that needs access to the DOM immediately after render inside that function. 在该函数中渲染之后,将需要访问DOM的所有内容立即放置在该函数中可能是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM