具有设置高度和溢出的jQuery slideDown

fxu*_*ser 10 html css jquery slidedown

我有以下HTML代码

<div class="text">bla bla bla bla</div>
<div class="button">Show</div>
Run Code Online (Sandbox Code Playgroud)

和CSS

.text{
  height:100px;
  overflow:hidden;
}
Run Code Online (Sandbox Code Playgroud)

假设.text div有更多文本,我所做的是隐藏100px以下的文本量.

我怎样才能slideDown()div这样我就可以查看文本,当我点击按钮?

使用$(".button").slideDown();不起作用,因为我需要删除高度,然后slideDown()这也无法正常工作.

小智 14

我喜欢Shankar的解决方案但是在前两次点击之后功能崩溃了.这是因为自动类被内联高度样式覆盖.所以我只更改了height属性.

这是我的理由:

$(".button").click(function(){
    $box = $(".text");
    minimumHeight = 100;

    // get current height
    currentHeight = $box.height();

    // get height with auto applied
    autoHeight = $box.css('height', 'auto').height();

    // reset height and revert to original if current and auto are equal
    $box.css('height', currentHeight).animate({
        height: (currentHeight == autoHeight ? minimumHeight : autoHeight)
    })
});
Run Code Online (Sandbox Code Playgroud)

一个缺陷是,如果你在盒子中添加填充物,你会得到一些难看的跳跃.打开任何解决方案来解决这个问题.

这是一个演示

非常欢迎改进和建议


Sha*_*oli 8

试试这个非常简单容易,不需要创建任何克隆.

$(function(){
    $(".button").click(function(){
        var $text = $(".text");
        var contentHeight = $text
                            .addClass('heightAuto').height();
        $text.removeClass('heightAuto').animate({ 
            height: (contentHeight == $text.height() ? 100 : contentHeight)
        }, 500);

    });
});
Run Code Online (Sandbox Code Playgroud)

添加了一个新课程

.heightAuto{
    height:auto;
}
Run Code Online (Sandbox Code Playgroud)

演示