高度自適應不能觸發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 大於正常高度就好了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM