高度自适应不能触发transition的解决方法

1. 前言 

  在我们不能确定一个元素的高度的时候,要使用transition过渡,是不会触发的,比如一个p标签 内容行数不固定  我们可能就要初始 height: 0 ; 过渡到 height: auto ;  写完发现并不能实现 。

  

可过渡的样式

  不是所有的CSS样式值都可以过渡,只有具有中间值的属性才具备过渡效果

 

  Vstart = 开始值; Vend = 结束值; Vres = 中间值; p = 过渡函数的输出值
  Vres = (1 - p) * Vstart + p * Vend
  当Vres具有有效值时,则该CSS样式可过渡


2. 解决方法(一个实例)
  通过设置max-height 来实现
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #div{
                max-height: 0;
                transition: .8s;
                overflow: hidden;
                border: 1px solid #000;
            }
            #btn{
                width: 50px;
                text-align: center;
                margin: 60px;
                line-height: 30px;    
                border: 2px solid #000;
                cursor: pointer;
            }
        </style>
    </head>
    <body>
        <div id="btn">
            点击我
        </div>
        <div id="div">
            asd <br/>
            asd <br/>
            asd <br/>
            asd <br/>
            asd <br/>
        </div>

        <script>
            btn.onclick = function(){
                if(div.on){
                    div.style.maxHeight = '0px';
                    div.on = false;
                }else{
                    div.style.maxHeight = '300px';
                    div.on = true;
                }
            }
        </script>
    </body>
</html>

 

因为max-height是根据内容来撑开高度的,只要max-height  大于正常高度就好了。

 

posted @ 2018-03-29 12:47  十年雪落  阅读(9382)  评论(0编辑  收藏  举报