如何设置'auto'JQuery动画中的高度

How to set 'auto' height in JQuery animate

本文关键字:动画 JQuery 高度 auto 何设置 设置      更新时间:2023-09-26

问题:我有一个固定宽度但未知(自动)高度的框(div)。

我需要使用JQuery animate函数打开/关闭该框。

问题是(代码中也有评论)在Open事件中,我需要设置自动高度,但我无法做到。有人能帮助将高度设置为自动吗?

JSFiddle:http://jsfiddle.net/7m5Qa/代码如下:

HTML

<button id="open">open</button>
<button id="close">close</button>
<div id="textselector-body">
    a<br/>
    b<br/>
    c<br/>
</div>​

Java脚本

$(document).ready(function(){
    $("#open").click(function(){
        $("#textselector-body").animate({
            height:'100px' //here is problem. I need it 'auto'.
        },2000);
    });
    $("#close").click(function(){
        $("#textselector-body").animate({
            height:'0'
        },2000);
    });
});​

您尝试过slideDown和slideUp吗?:

$(document).ready(function(){
    $("#open").click(function(){
        $("#textselector-body").slideDown(2000);
    });
    $("#close").click(function(){
        $("#textselector-body").slideUp(2000);
    });
});​

jsFiddle:http://jsfiddle.net/7m5Qa/2/

您尝试过height:'toggle'吗?(JQuery.animate())

不过,只要你点击按钮,它就会反转转换,但如果你只想要一个按钮,那就是解决方案。

演示

您可以将.slideUp和.slideDown方法与jQuery:一起使用

$("#open").click(function(){
        $("#textselector-body").slideDown('slow')
});
    $("#close").click(function(){
        $("#textselector-body").slideUp('slow')
});

http://jsfiddle.net/Kyle_Sevenoaks/7m5Qa/3/

$(document).ready(function(){
    var H = $("#textselector-body").height();
    $("#open").click(function(){
        $("#textselector-body").animate({
            height:'100px'
        },2000);
    });
    $("#close").click(function(){
        $("#textselector-body").animate({
            height:H
        },2000);
    });
});​

FIDDLE

编辑:

不确定我是否答对了问题?如果你只是想切换它,你可以做:

$(function(){
    $("#open, #close").click(function(e){
        $("#textselector-body")[e.target.id=='open'?'slideDown':'slideUp'](2000);
    });
});​

FIDDLE