Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - jquery .ready and height of element

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...