[英]Calculate height according to div's inner text
我有一個PHP循環來創建多個div,這些div顯示數據庫中的數據。
<?php
foreach($result as $row) {
?>
<div class="container-fluid" id="content-fluid">
<div class="container-update">
<div class="update-group">
<div class="update-header">
<?php echo $row['update_title'] ?>
<div class="update-author">
by <?php echo $row['update_creator'] ?>
</div>
</div>
<div class="update-body">
<?php echo $row['update_text']; ?>
</div>
</div>
</div>
</div>
<?php
}
?>
我通過jQuery使它們可點擊,並且它們的高度確實增加了:
$(document).ready(function() {
$('.update-group').click(function() {
var clicks = $(this).data('clicks');
if(clicks) {
$(this).removeAttr('style');
}
else {
$(this).animate({height: '200px'}, 300);
}
$(this).data("clicks", !clicks);
});
});
默認高度設置為特定值,以確保所有div都具有相同的高度,並且溢出設置為隱藏。 單擊它們應根據其中的文本向下擴展它們。
文本適合的Divs應該根本不能擴展。 並且包含過多文本的div應該擴展到計算出的高度。
我已經建立了一個jsfiddle程序來演示我的意思: https ://jsfiddle.net/vz6s9brd/
現在,它只是動畫到200px並返回。 我認為您正在尋找這樣的東西:
$('.update-group').click(function() {
var clicks = $(this).data('clicks');
if(clicks) {
$(this).removeAttr('style');
}
else {
var bod = $(this).find('.update-body');
var head = $(this).find('.update-header');
var neededHeight = bod.height() + head.height();
if ($(this).height() < neededHeight) {
$(this).animate({height: neededHeight + 'px'}, 300);
}
}
$(this).data("clicks", !clicks);
});
除了計算高度外,您還可以更改溢出設置。 您想在兩種模式之間進行切換-一種模式具有有限的高度且沒有溢出,而另一種模式則具有由內容決定的高度。
if(clicks) {
$(this).css({overflow: 'hidden', height: '6em'});
}
else {
$(this).css({overflow: 'inherit', height: '100%'});
}
不幸的是,以這種方式進行動畫效果不佳。 即使將上面的css()
調用替換為對animate()
調用,結果也不令人滿意。 動畫對您的重要性取決於您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.