1

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

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

问题是(在代码中也有注释)打开事件,我需要设置自动高度,这是我无法做到的。有人可以帮助将高度设置为自动吗?

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);
    });
});​
4

4 回答 4

5

你试过 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/

于 2012-08-24T08:38:00.450 回答
2

你试过height:'toggle'吗?( jQuery.animate() )

它会在您单击按钮时反转转换,但如果您只想要一个按钮,它就是解决方案。

演示

于 2012-08-24T08:49:26.927 回答
1
$(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);
    });
});​

小提琴

编辑:

不确定我的问题是对的吗?如果你只是想切换它,你可以这样做:

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

小提琴

于 2012-08-24T08:36:30.167 回答
1

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

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

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

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

于 2012-08-24T08:38:09.510 回答