Javascript / jQuery:当max-height设置为0时获取高度

时间:2013-08-06 14:38:50

标签: javascript jquery height css

height设置为0时,是否可以获取元素的at max-height的css值?

我需要知道要显示多少像素的元素,因为每个元素都有不同的高度,随着浏览器的大小而变化,我想从css文件中获取高度值。

http://jsfiddle.net/AqAJc/

4 个答案:

答案 0 :(得分:5)

如果通过scrollHeight属性有max-height = 0,则可以获取元素的高度。如果你设置了最小重量,它可以工作,但不是高度。

HTML:

<div>
  Here you have a normal div
  <div id="toggable">
    Something hidden is in here, but we can still get the height !
    <div class="other-content">
      Something else here
    </div>
  </div>
</div>

JS:

alert(document.getElementById('toggable').scrollHeight)

CSS:     #toggable {       最大高度:0;       溢出:隐藏;     }

.other-content {
  min-height: 100px;
}

演示:https://jsfiddle.net/asywL84u/2/

参考:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

答案 1 :(得分:2)

我的第一个问题是为什么你使用max-height: 0;还有其他什么可以使用?与使用hide()

show() display: none一样

唯一可以解决的问题是移除max-height css获取高度,然后重新应用max-height:

$('.div').css('max-height', 'none')
console.log($('.div').height())
$('.div').css('max-height', '0')

这应该足够快,你不会看到元素,但在删除max-height之前隐藏它是明智的:

$('.div').hide()
$('.div').css('max-height', 'none')    
console.log($('.div').height())
$('.div').css('max-height', '0')
$('.div').show()

答案 2 :(得分:1)

$('.div').each(function(){
    var t=$(this); // Cache jQuery reference
    t.css('max-height','none'); // Temporarily override max-height
    t.data('height',t.height()); // Store height in data
    t.css('max-height',''); // Remove our max-height override
});
alert($('.div').data('height'));

jsfiddle:http://jsfiddle.net/AqAJc/7/

答案 3 :(得分:0)

将最大高度保留在css之外。在变量中缓存高度。然后再次将max-height添加到0。

$(function(){
    var divHeight = $('.div').height();
    $('.div').css('max-height', '0');
    alert(divHeight);
});

http://jsfiddle.net/AqAJc/4/