需要在页面上找到隐藏div的高度(设置为display:none) [英] Need to find height of hidden div on page (set to display:none)
问题描述
我需要测量一个隐藏元素内的div的offsetHeight。
I need to measure the offsetHeight of a div that is inside of a hidden element.
<div id="parent" style="display: none;">
<div id="child">Lorem Ipsum dolor sit amet.</div>
</div>
父div 必须设置为 display:none
。我没有控制权。我意识到,孩子的div的offsetHeight将为0.我需要找到一个解决方法。
The parent div must be set to "display:none
". I have no control over that. I realize that the offsetHeight of the child div is going to be 0. I need to find a workaround.
我玩过的东西是当页面加载,我复制父节点的子节点,注入设置为 visiblity:hidden
的页面上的div。然后我测量这些元素的高度,并删除完成后的节点。
Something I've toyed with is when the page loads, I copy the childnodes of parent, inject in a div on the page that is set to "visiblity:hidden
". Then I measure the height of those elements, and remove the nodes when done.
任何其他想法?
更新:
必须做的是这样的:
Update: What I wound up having to do was this:
使用YUI 2,在页面加载,我发现给定的类名称的所有元素被设置为显示:无,和width为0(这是一种测量元素是否存在或父设置为display:none的方法)。然后我将该元素设置为display:block。然后我检查它的父对同样的事情,并显示父母,直到它找到一个可见的父。一旦最高显示:none ancestor设置为display:block,我可以测量我的元素。
Using YUI 2, on page load, I found all elements of that given classname that were either set to display:none, or whose height and width was 0 (that's one way of measuring whether an element exists, or a parent is set to display:none). I then set that element to display:block. I then checked it's parent for the same thing and showed the parents until it finds a visible parent. Once highest display:none ancestor is set to display:block, I can measure my element.
测量所有元素后,我将所有元素重置为显示:none 。
Once all elements are measured I reset all of the elements back to display:none.
推荐答案
您需要让元素的父级可见获取元素的维度。在一个通用的解决方案中,所有的祖先通常被遍历,并使其可见。然后,他们的显示
值被设置回原来的。
You need to make element's parent visible for that one very short moment while you're getting element's dimensions. In a generic solution, all ancestors are usually traversed and are made visible. Then their display
values are set back to original ones.
当然有性能问题。
我们在Prototype.js实现中考虑了这种方法,但最终以 getWidth
和 getHeight
仅使实际元素可见,而无需遍历祖先。
We considered this approach in Prototype.js implementation but ended up with getWidth
and getHeight
making only actual element visible, without traversing ancestors.
替代解决方案的问题 - 例如将元素从隐藏父项中移除 - 是某些样式可能不再适用于一个元素, 层次。如果您有这样的结构:
The problem with alternative solutions - such as taking element out of "hidden" parent - is that certain styles might no longer apply to an element once it's out of its "regular" hierarchy. If you have a structure like this:
<div class="foo" style="display:none;">
<div class="bar">...</div>
</div>
这些规则:
.bar { width: 10em; }
.foo .bar { width: 15em; }
然后将元素从其父级中移除将会导致尺寸错误。
then taking element out of its parent will actually result in wrong dimensions.
这篇关于需要在页面上找到隐藏div的高度(设置为display:none)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!