鼠标hover
时使一个未知高度元素的高度从0
过渡到auto
。
本实现的思路是:
js
提前将元素的scrollHeight
保存在CSS变量--max-height
中。hover
时max-height直接
使用--max-height
保存的值。<div class="trigger">
恭喜发财
<div class="el">红包拿来</div>
</div>
.el {
transition: max-height 0.5s;
overflow: hidden;
max-height: 0;
}
.trigger:hover > .el {
max-height: var(--max-height);
}
let el = document.querySelector('.el');
let height = el.scrollHeight;
el.style.setProperty('--max-height', height + 'px');
-transition:max-height:0.5s
使用默认的ease
时间函数在0.5
秒内过渡max-height
的值。
-overflow:hidden
防止超出max-height
范围内的子元素内容溢出容器。
-max-height:0
指定元素初始的最大高度为0
。
-.target:hover> .el
指定当hover
父级元素时,使其子节点.el
的max-height
为CSS变量--max-height
的值。
-el.scrollHeight
指元素包含滚动部分的高度,它将根据元素的内容动态变化。
-el.style.setProperty(...)
设置--max-height
CSS变量的值为元素的scrollHeight
。
以下两点需要注意:
reflow
),所以当需要改变高度的元素内包含大量元素时,会造成动画效果滞后。CSS变量
已经得到大部分主流浏览器的支持,但是IE
除外。兼容性如下: