【问题标题】:How to set 'auto' height in JQuery animate如何在 JQuery animate 中设置“自动”高度
【发布时间】:2012-08-24 08:34:04
【问题描述】:

问题: 我有一个固定宽度但未知(自动)高度的框(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);
    });
});​

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

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

    【讨论】:

    • 感谢gabitzish,这似乎是更好的解决方案。很高兴我在这里问它而不是修复自己。必须为我的新事物 +1。
    【解决方案2】:

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

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

    DEMO.

    【讨论】:

      【解决方案3】:

      您可以在 jQuery 中使用 .slideUp 和 .slideDown 方法:

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

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

      【讨论】:

      • 感谢凯尔,这似乎是更好的解决方案。很高兴我在这里问它而不是修复自己。必须为我的新事物 +1。
      【解决方案4】:
      $(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

      【讨论】:

      • 感谢您的快速答复。肯定 +1。
      • @KapilSharma - 基于其他答案,我想我不太明白,我假设你在哪里试图扩展高度并回到自动高度等。如果只是想切换其他答案都可以,我也为此添加了解决方案?
      猜你喜欢
      • 2015-05-11
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 2021-11-02
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      相关资源
      最近更新 更多