当元素的
height
设置为0时,是否可以获取元素的attrmax-height
的css值?
我需要这个来知道单击时要显示多少像素的元素,并且由于每个元素都有不同的高度,随着浏览器大小的变化,我想从 css 文件中获取高度值。
如果max-height = 0,则可以通过scrollHeight属性获取元素的高度。如果您设置最小高度,但不是高度,它会起作用。
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 {
max-height:0;
overflow:hidden;
}
.other-content {
min-height: 100px;
}
演示:https://jsfiddle.net/asywL84u/2/
参考:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight
我的第一个问题是你为什么使用
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()
$('.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/
保留 CSS 的最大高度。将高度缓存在变量中。然后再次将
max-height
添加到 0。
$(function(){
var divHeight = $('.div').height();
$('.div').css('max-height', '0');
alert(divHeight);
});
试试这个:
document.querySelector("#animated-max-height").style.setProperty("--visible-height", document.querySelector("#get-alway-visible-height").clientHeight + "px");
document.querySelector("#animated-max-height").style.setProperty("--content-height", document.querySelector("#animated-max-height").scrollHeight + "px");
#animated-max-height {
max-height: var(--visible-height);
padding: 0px;
transition: max-height 1s ease-out;
overflow: hidden;
}
#animated-max-height:hover {
max-height: var(--content-height);
}
<div id="animated-max-height">
<div id="get-alway-visible-height">Hover me</div>
<div>Now you see me</div>
</div>