首页 > 解决方案 > 通过“闪烁”到自动获得最终值的动画元素高度

问题描述

我正在尝试将元素的高度从预设高度设置为取决于内部内容(height: auto设置内容)的高度。因为动画不适用于height: auto(往返)我认为解决方案可能是保存当前高度,height: auto在元素上设置以获取最终高度并保存,然后将元素的高度重置为初始高度,然后设置它到最后的高度。用户不会注意到“自动闪烁”,最后一次更改应该会产生动画。

const containerBlockDiv = document.querySelector('.container-block')
const childBlockDiv = document.querySelector('.child-block')

const containerCurrentHeight = containerBlockDiv.scrollHeight
containerBlockDiv.style.height = 'auto'
const containerNewHeight = containerBlockDiv.scrollHeight
containerBlockDiv.style.height = `${containerCurrentHeight}px`
containerBlockDiv.style.height = `${containerNewHeight}px`
.container-block {
  display: inline-block;
  background-color: red;
  height: 50px;
  width: 20px;
  transition: height 1s;
}

.child-block {
  display: inline-block;
  height: 100px;
}
<div class="container-block">
  <div class="child-block"></div>
</div>

为什么这不起作用?

标签: javascriptcss

解决方案


这是我在我的法术书中将 div 从 0(或任何其他固定值)动画到auto:纯 CSS,无 JS

div {
  max-height: 15px;
  overflow: hidden;
  border: red dashed 1px;
  transition: max-height 0.3s cubic-bezier(0, 1, 0, 1);
}

div:hover {
  max-height: 9999px;
  transition: max-height 0.3s cubic-bezier(1, 0, 1, 0);
}
<div>Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some
  content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content
  Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content</div>


推荐阅读