jQuery的.ready和元素的高度 [英] jquery .ready and height of element

查看:95
本文介绍了jQuery的.ready和元素的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能看起来像一个微不足道的问题,但我在使用jQuery时遇到了一个问题。当我尝试获取.ready中元素的高度时,我总是给出零。

  $(function(){ 
$('#my-elem')。height()//总是给我零。
});

如果我在高度检查(例如.5s)周围用setTimeout()那么高度正确地报告给我。我猜这是因为样式还没有机会被应用呢?

我发现这个问题的唯一解决方案是使用一个间隔来轮询元素的高度,直到它变成非零,但这对我来说似乎矫枉过正。有没有更好的方法?

解决方案

document.ready 事件信号HTML DOM已准备好通过Javascript访问,但并不意味着元素已经呈现

实际上,这就是code> ready 之后的整个shebang:这是一种让您无需等待页面完成加载即可开始操作文档的HTML DOM 的方法。假设在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆