javascript - 通过“闪烁”到自动获得最终值的动画元素高度
问题描述
我正在尝试将元素的高度从预设高度设置为取决于内部内容(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>
为什么这不起作用?
解决方案
这是我在我的法术书中将 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>
推荐阅读
- multithreading - How to load a large .yml file to predict a face using python's opencv?
- javascript - how could I change the opacity of a div?
- mysql - MySQL查询到列的唯一组合
- php - 如何将多个值从laravel中的控制器传递给路由
- javascript - 如何从 vanilla js 中的多个 ajax 调用中累积数据
- angular - 更改 .ts 文件中的值并将其保存在 app ionic 中
- angularjs - 具有多个条件的 ng-class
- android - 谷歌插件服务给了我一个错误
- r - 根据单独的索引重命名行
- python - pandas DataFrame 上的位置字符串格式