一個元素不設置高度時,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 lang="en"> <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 id="box">...</div> <p> <input type="button" id="button" value="點擊我"> </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; };