javascript jquery .ready 和元素的高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11115179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery .ready and height of element
提问by backdesk
Might seem like a trivial question but I've run into an issue while using jQuery. When I try and get the height for an element within a .ready I am always given zero.
似乎是一个微不足道的问题,但我在使用 jQuery 时遇到了一个问题。当我尝试获取 .ready 中元素的高度时,我总是得到零。
$(function() {
$('#my-elem').height() // Always gives me zero.
});
If I put code in a delay with setTimeout() around the height check (say of .5s) then the height is correctly reported back to me. I'm guessing that this is because the styles haven't had a chance to be applied yet?
如果我在高度检查周围使用 setTimeout() 延迟代码(比如 0.5s),那么高度会正确报告给我。我猜这是因为样式还没有机会应用?
The only solution I've found to this problem is to use an interval to poll the height of the element until it becomes non-zero but this seems overkill to me. Is there a better way?
我发现这个问题的唯一解决方案是使用一个间隔来轮询元素的高度,直到它变为非零,但这对我来说似乎有点过分。有没有更好的办法?
回答by Richard Neil Ilagan
The document.ready
event signals that the HTML DOM is ready for accessing via Javascript, but that doesn't mean that the elements have already rendered.
该document.ready
事件表示 HTML DOM 已准备好通过 Javascript 进行访问,但这并不意味着元素已经呈现。
In fact, that's the whole shebang behind ready
: it's a means for you to start manipulating your document's HTML DOM without having to wait for the page to finish loading. It's safe to assume that at document.ready
, your elements are not yet displayed on the page.
事实上,这就是背后的全部内容ready
:它是一种让您无需等待页面完成加载即可开始操作文档的 HTML DOM 的方法。可以安全地假设在document.ready
,您的元素尚未显示在页面上。
Now, that comes with a caveat: if the elements haven't rendered yet, how can the browser / Javascript know what its resolving height is? .height()
may give zero at document.ready
because of this. It's probably best to wait until load
instead of ready
when it comes to pulling box dimensions from the layout.
现在,有一个警告:如果元素还没有呈现,浏览器/Javascript 怎么知道它的解析高度是多少?.height()
因此可能会给出零document.ready
。最好等到从布局中提取框尺寸时,load
而不是等到ready
。