【问题标题】:jQuery: How to animate height change without known heights?jQuery:如何在没有已知高度的情况下动画高度变化?
【发布时间】:2014-03-19 20:17:01
【问题描述】:

我想使用 jQuery 对高度变化进行动画处理(当我隐藏/显示 div 时)。我在 SO 上找到了一些示例,但我无法让它们发挥作用。

假设我有一个容器,里面有一些 div。

HTML:

<div class="container">
  <div class="first">Show first div</div>
  <div class="second">Show second div</div>
  <div class="item1">
     Some text
  </div>
  <div class="item2">    
     Some multiline<br />text
  </div>
</div>

jQuery:

$('.first').on('click',function(){
  $('.item2').hide();
  $('.item1').show();
});
$('.second').on('click',function(){
  $('.item1').hide();
  $('.item2').show();
});

http://jsfiddle.net/ytW69/2/

当我单击 div .first 时,我想显示 div .item1,当我单击 div .second 时,我想显示 div .item2。这些 div 的高度不同,这意味着当我隐藏/显示 div 时,容器的大小会发生变化。

如何在不知道任何 div 大小的情况下为这种高度变化设置动画?

ps。如果有 CSS 解决方案,那就更好了。我认为仅使用 CSS 是不可能的。

【问题讨论】:

    标签: jquery html css animation


    【解决方案1】:

    使用.show().hide()的可选参数,可以实现你想要的动画效果。您也可以将该参数作为milliseconds 传递。

    试试,

    $('.first').on('click',function(){
        $('.item2').hide('slow');
        $('.item1').show('slow');
    });
    $('.second').on('click',function(){
        $('.item1').hide('slow');
        $('.item2').show('slow');
    });
    

    DEMO

    【讨论】:

    • @RobinvdA 很高兴为您提供帮助!
    【解决方案2】:

    你可以试试这个:-

    $('.first').on('click',function(){
        $('.item2').hide('fast');
        $('.item1').show('fast');
    });
    $('.second').on('click',function(){
        $('.item1').hide('fast');
        $('.item2').show('fast');
    });
    

    当您提供 fastslow 之类的字符串值时,.show() 将成为动画方法。 .show() 方法同时为匹配元素的宽度、高度和不透明度设置动画。

    【讨论】:

      【解决方案3】:

      如果你想要更好看的效果(在我看来),你可以使用slideDown()slideUp()

      $('.first').on('click', function () {
          $('.item1:hidden').slideDown('slow');
          $('.item2:visible').slideUp('slow');
      });
      
      $('.second').on('click', function () {
          $('.item2:hidden').slideDown('slow');
          $('.item1:visible').slideUp('slow');
      });
      

      查看此JSFiddle 演示以获得结果。

      【讨论】:

        【解决方案4】:

        您正在寻找的 CSS 解决方案是使用最大高度和/或最小高度。 这可能会有所帮助: css3 height transition on an absolute positioned div to overflow auto fails

        【讨论】:

        • 我遇到了一些使用最大/最小高度的解决方案。但是我的页面不能有高度,甚至没有最大高度
        猜你喜欢
        • 2015-02-27
        • 2011-01-28
        • 2013-06-06
        • 1970-01-01
        • 2016-12-29
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 2013-03-18
        相关资源
        最近更新 更多