jQuery的.ready和元素的高度 [英] jquery .ready and height of element
问题描述
$(function(){
$('#my-elem')。height()//总是给我零。
});
如果我在高度检查(例如.5s)周围用setTimeout()那么高度正确地报告给我。我猜这是因为样式还没有机会被应用呢?
我发现这个问题的唯一解决方案是使用一个间隔来轮询元素的高度,直到它变成非零,但这对我来说似乎矫枉过正。有没有更好的方法?
document.ready
中,您的元素尚未显示在页面上是安全的。 现在,这是一个警告:如果元素还没有渲染,那么浏览器/ Javascript怎么知道它的分辨高度是多少?因此, .height()
可能在 document.ready
处为零。当涉及到从布局拉动框尺寸时,最好等到加载
而不是就绪
。
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.
$(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?
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?
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.
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.
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.
这篇关于jQuery的.ready和元素的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!