根据div的内部文本计算高度 [英] Calculate height according to div's inner text

查看:115
本文介绍了根据div的内部文本计算高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP循环来创建多个显示数据库数据的div。

I've got a PHP loop to create multiple divs which display data from a database.

<?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使他们可以点击,他们的身高增加:

I made them clickable through jQuery and they do increase in height:

        $(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具有相同的高度,设置为隐藏。点击它们应该根据其中的文本向下扩展它们。

Default height is set to a specific value to ensure that all divs are of the same height and overflow is set to hidden. Clicking on them should expand them downwards according to the text inside of it.

其中文本适合的div,应该不能展开。

Divs of which the text fits just fine, shouldn't be able to expand at all. And divs with an excessive amount of text should expand to a calculated height.

我设置了一个jsfiddle程序来演示我的意思: https://jsfiddle.net/vz6s9brd/

I've set up a jsfiddle program to demonstrate what I mean: https://jsfiddle.net/vz6s9brd/

推荐答案

现在它只是动画到200px和回来。我想你正在寻找这样的东西:

Right now it just animates to 200px and back. I think you're looking for something like this:

$('.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);
});

这篇关于根据div的内部文本计算高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆