javascript - jQuery 将 div 的高度设置为有多少文本

标签 javascript jquery html css

我已经构建了一个简单的动画功能,您可以在其中单击一个扩展框,如果可能的话我宁愿不使用插件。

目前它看起来像这样:

$('#one').css("height", "22");
    $('#t1').click(function() {
      if ($('#one').hasClass("extended")) {
        $('#one').stop(true, true).animate({height: '22px'},500);
        $('#one').removeClass("extended");
        $('#a1').stop(true, true).animate({opacity: '1'},500);
      } else {
        $('#one').animate({height: '120px'},500);
        $('#one').addClass("extended");
        $('#a1').animate({opacity: '0'},300);
      }
});

但问题是,如果div里面的文字溢出了,那怎么设置为文字的高度呢?我希望这是有道理的!

HTML:

<div class="rightBox">
    <div id="one" style="overflow:hidden;">
        <h3><a href="#" id="t1">Availability</a></h3><p id="a1"><a href="#" title="Slide Down"><img src="<?php echo home_url(); ?>/img/arrow.png" alt="Arrow" /></a></p>
        <?php include 'availability.php'; ?>
    </div>
</div><!-- END.#rightBox -->

最佳答案

我处理这个问题的方法是计算所有 child 的高度,然后开始动画到那个特定的高度。见下文。

查看此 jsFiddle .

<div class="rightBox">
    <div id="one" style="overflow:hidden;">
        <h3><a href="#" id="t1">Availability</a></h3><p id="a1"><a href="#" title="Slide Down"><img src="/img/arrow.png" alt="Arrow" /></a></p>
        <p>Sample text</p>        
                <p>Sample text</p>        
                <p>Sample text</p>        
                <p>Sample text</p>        
                <p>Sample text</p>        
                <span>More Sample text</span>        
    </div> </div>​

jQuery/javascript

$('#one').css({"height": "22px", "background-color": "red"});

    $('#t1').click(function() {

      if ($('#one').hasClass("extended")) {
        $('#one').stop(true, true).animate({height: '22px'},500);
        $('#one').removeClass("extended");
        $('#a1').stop(true, true).animate({opacity: '1'},500);
      } else {
        var height = 0;//initialize a height
        $(this).closest("div").children().each(function(){//this loops through each child element
           height += $(this).outerHeight(true);//this sums up the height
        });
        $('#one').animate({height: height + 'px'},500);//set the height
        $('#one').addClass("extended");
        $('#a1').animate({opacity: '0'},300);
      } });​

关于javascript - jQuery 将 div 的高度设置为有多少文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13088477/

相关文章:

javascript - 打破经典的 ASP 页面

javascript - 来自 ajax 的模型绑定(bind),用于将日期值传递为 null

javascript - jQuery渐变下沉效果按钮

javascript - 在 jquery 代码中的何处插入 PreventDefault

Javascript |创建一个在页面关闭前触发的弹出窗口

实现定义标识符的 JavaScript 约定

javascript - 调整大小后获取 Gridster 小部件的新大小

javascript - Ionic AngularJS 所有 ng-click 事件都触发两次?

javascript - html5文件上传

javascript - HTML 创建一个包含在新窗口中打开链接的按钮