不定高度的元素实现transition动画_如何为height:auto的div添加css3过渡动画?

一个元素不设置高度时,height的默认值是 auto,浏览器会自动计算出实际的高度。那么如何为一个height:auto的元素添加 css3动画呢?在MDN文档中css 支持动画的属性中的 height 属性如下 :当 height 的值是 length,百分比或 calc() 时支持 css3 过渡,所以当元素 height : auto 时,默认是不支持 css3 动画的。

为了解决这个问题,我们可以通过js 获取精确的 height 值,或者使用max-height 代替 height。只需要设置一个肯定比元素自增长大的高度值,由于是根据 max-height 值进行过渡效果,所以最好不要大得离谱,否则动画效果不理想。下面就介绍这2种方式的实现:

1、利用max-height:

<!DOCTYPE html>
<html >
    <head>
        <meta charset="utf-8">
        <style>
            *{
                margin: 0;
                padding:0;
            }
            div{
                
                display: inline-block;
                overflow: hidden;
                background-color: orange;
                max-height: 20px;
                -webkit-transition: max-height 1s;
                transition: max-height 1s;
            }
            div:hover{
                max-height:200px;
            }
        </style>
    </head>
    <body>
        <div>
            <p>我不是height,是max-height</p>
            <p>我不是height,是max-height</p>
            <p>我不是height,是max-height</p>
            <p>我不是height,是max-height</p>
            <p>我不是height,是max-height</p>
            <p>我不是height,是max-height</p>
        </div>
    </body>
</html>

  

2、通过js获取高度

css:

.box { width: 400px; padding: 20px; border: 40px solid #a0b3d6; background-color: #eee; overflow: hidden; }
.loading { height: 100%; background: url(loading.gif) no-repeat center; }
.in { width: 100px; margin: 0 auto;  border: 50px solid #beceeb; background-color: #f0f3f9; }
[type=button] { width: 100px; height: 32px; font-size: 100%; }

资源网站大全 https://55wd.com 设计导航https://www.wode007.com/favorites/sjdh

html:

<div >...</div>
<p>
    <input type="button" >
</p>

  

js:

// 高度无缝动画方法
var funTransitionHeight = function(element, time) { // time, 数值,可缺省
    if (typeof window.getComputedStyle == "undefined") return;
    
    var height = window.getComputedStyle(element).height;

    element.style.transition = "none";    // 本行2015-05-20新增,mac Safari下,貌似auto也会触发transition, 故要none下~
   
    element.style.height = "auto";
    var targetHeight = window.getComputedStyle(element).height;
    element.style.height = height;
    element.offsetWidth = element.offsetWidth;
    if (time) element.style.transition = "height "+ time +"ms";
    element.style.height = targetHeight;
};