元素高度不确定时实现height从0到auto动画

Published on with 0 views and 0 comments

原理

  • CSS transition只适用于明确的值,auto这种无法实现过度
  • CSS var()函数可以代替元素中任何属性中的值的任何部分

答案

HTML部分

<div class="trigger">
  Hover me to see a height transition.
  <div class="el">content</div>
</div>

CSS部分

.el {
  transition: max-height 0.5s;
  overflow: hidden;
  max-height: 0;
}

.trigger:hover > .el {
  max-height: var(--max-height);
}

JavaScript部分

var el = document.querySelector('.el')
var height = el.scrollHeight
el.style.setProperty('--max-height', height + 'px')

标题:元素高度不确定时实现height从0到auto动画
作者:lj0812
地址:https://blog.hereis.me/articles/2019/08/01/1564656287489.html