寻找一个JavaScript解决方案(jQuery就好了)来获得一些div的高度,这些div都位于父div中,并将display设置为none。
伪代码:
<div id="hiddenParent" style="display:none">
<div class="childDiv">child div 1</div>
<div class="childDiv">child div 2</div>
<div class="childDiv">child div 3</div>
</div>假设类ChildDiv没有指定高度,也没有设置任何childDiv元素的高度。
当"hiddenParent“设置为display:none时,如何获得他们的身高?
发布于 2012-09-01 01:55:18
var clone = $("#hiddenParent").clone().css("display","block").css("position","absolute").css("left","-9999px");
$("#hiddenParent").after(clone);
alert(clone.outerHeight());
clone.remove();
使用jQuery。
发布于 2012-09-01 01:55:15
试着看看jQuery: Get height of hidden element in jQuery
关于这个问题有很多很好的帖子。
发布于 2014-06-18 07:16:39
虽然聚会迟到了,但不管怎样,我还是会接受这件事的。下面的解决方案是用Vanilla Javascript编写的,但同样的逻辑显然也适用于jQuery。
元素不一定需要是可见的才能被测量,它们只需要而不是是display: none;。Display:none表示计算样式中的高度为0,因此我们必须找到解决方法。
我们可以通过两个简单的步骤来模拟display:none:
visibility:hidden (这样元素不可见)position:absolute (这样元素不占用空间)然后,我们将其display设置为block (或空字符串,只要它不是none,这并不重要)。然后我们将有一个不可见的div,它不会占用文档中的空间,但会保留它自己的原始尺寸。这样,即使之前没有在css中设置维度,也可以通过JavaScript完全访问它。
在一个循环中,我们将对每个我们需要的div运行getComputedStyle,查找它的高度。
// start loop
getComputedStyle(el).getPropertyValue('height');
// end loop如果您仍然需要在循环结束时将显示设置为none,则可以恢复它。脚本并不复杂,运行时没有任何闪动。
这是一个demo。
var par = document.getElementById('hiddenParent'),
cd = par.querySelectorAll('.childDiv'),
len,
heights = [],
i;
function getHeight(){
len = cd.length;
// 1.we hide the parent
par.style.visibility = 'hidden';
// 2. we set its position to absolute, so it does not
// take space inside the window
par.style.position = 'absolute';
// 3. we set its display to block so it will gain back its natural height
par.style.display = 'block';
// 4. we start looping over its children
while(len--){
// we get the height of each children... here we're just storing them in array,
// which we will alert later
heights[len] = window.getComputedStyle( cd[len] ).getPropertyValue('height');
}
// 5. Job is done, we can bring back everything to normal (if needed)
par.cssText = 'display: none';
}
document.getElementById('starter').addEventListener('click',function(){
getHeight();
alert(heights);
});#hiddenParent, .another-div{
background: teal;
width: 40%;
padding: 20px;
text-align: center;
color: white;
font-family: Arial;
text-transform: uppercase;
color: #ccc;
}
.childDiv{
background: purple;
padding: 10px;
margin-bottom: 10px;
}
.another-div{
background: orange;
color: #1F9091;
}<button id="starter"> Calculate heights </button>
<!-- hiddenParent is between two other divs but takes no space in the document as it's display:none -->
<div id="hiddenParent" style="display: none;">
<div class="childDiv">child div 1</div>
<div class="childDiv">child div 2</div>
<div class="childDiv">child div 3</div>
</div>
<div class="another-div">
here's another div
</div>
https://stackoverflow.com/questions/12220304
复制相似问题