問題出處:http://stackoverflow.com/quest......eight-and-overflow
有個 HTML 是這樣:
檢視原始碼 HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <body> <div class="text"> 這是一段很~~<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 很<br /> 長的區塊 </div> <div class="button">Show</div> </body> |
然後 .text 是設定成:
檢視原始碼 CSS
1 2 3 4 | .text{ height: 100px; overflow: hidden; } |
.text 區塊高度被固定 100px 了,而其它超出的範例是因為 overflow: hidden; 被隱藏的。所以原發問者的問題是想要讓 .text 能滑動展開完整的高度。
之前筆者是會再用另一個區塊來包裹並做一些手腳,但 ShankarSangoli 利用神不知鬼不覺的 height: auto; 來取得完整高度後再進行處理:
檢視原始碼 JavaScript
1 2 3 4 5 6 7 8 9 10 | $(function(){ $(".button").click(function(){ var $text = $(".text"); var contentHeight = $text.addClass('heightAuto').height(); $text.removeClass('heightAuto').animate({ height: (contentHeight == $text.height() ? 100 : contentHeight) }, 500); }); }) |
不過這缺點會在因為當縮回去時寫死高度了,變成執行一次展開收合後就會失效了。所以若能在第一次展開時就把完整高度記錄起來的話,也許就簡單多了:
檢視原始碼 JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $(function(){ $(".button").click(function(){ var $text = $(".text"); // 先取得是否有記錄在 .data('contentHeight') 中 var contentHeight = $text.data('contentHeight'); // 若沒有記錄 if(!!!contentHeight){ // 取得完整的高 contentHeight = $text.addClass('heightAuto').height(); // 並記錄在 .data('contentHeight') 中 $text.data('contentHeight', contentHeight).removeClass('heightAuto'); } // 進行折疊 $text.stop().animate({ height: (contentHeight == $text.height() ? 100 : contentHeight) }, 500); }); }) |
至於 Kato 則是複製一個完整的 .text 區塊後,再取得該複製區塊的完整高度來使用:
檢視原始碼 JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 | $(function(){ $('.button').click(function() { var $div = $('div.text'); $div.animate({height: determineActualHeight($div)}); }); function determineActualHeight($div) { var $clone = $div.clone().hide().css('height', 'auto').appendTo($div.parent()), height = $clone.height(); $clone.remove(); return height; } }) |
這是一個很有趣但是有點耗效能的用法,所以筆者也一樣是在第一次取得完整高度時就先記錄起來:
檢視原始碼 JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | $(function(){ $('.button').click(function() { var $div = $('div.text'); // 先取得是否有記錄在 .data('contentHeight') 中 var contentHeight = $div.data('contentHeight'); // 若沒有記錄 if(!!!contentHeight){ // 取得完整的高 contentHeight = determineActualHeight($div); // 並記錄在 .data('contentHeight') 中 $div.data('contentHeight', contentHeight); } // 進行折疊 $div.stop().animate({ height: (contentHeight == $div.height() ? 100 : contentHeight) }, 500); }); function determineActualHeight($div) { var $clone = $div.clone().hide().css('height', 'auto').appendTo($div.parent()), height = $clone.height(); $clone.remove(); return height; } }) |
但如果 .text 區塊的內容是會一直動態改變的話,筆者是建議採用每次複製區塊的方式來取得高度,這樣的高度才能時時更新。