jquery - 在 jQuery 中,如何为 "max-height"CSS 属性设置动画?

标签 jquery css jquery-animate

我可以轻松地为“不透明度”属性设置动画

$("#blah").animate({ opacity: 0.5}, 1000);

如何为 max-height css 属性设置动画...示例:

$("#blah").animate({ "max-height": 350}, 1000);

(提示,该代码不起作用)

编辑:回答以下问题:

  1. 有多个图像都是 css 类“blah”
  2. 图片的大小是随机的,但它们的最大高度都是:100px
  3. 当用户将鼠标悬停在图像上时,我希望它为最大高度设置动画(从而顺利取消限制高度)

最佳答案

这个问题有点老了,但这是我使用基本 jQuery 解决它的方法,以防其他人需要一个简单的解决方案。

在我的例子中,我有一个博客文章列表,首先使用 max-height 呈现给页面,它只显示前 4 行文本,其余的是 overflow : 隐藏。我有一个展开/折叠按钮,可将文章从折叠形式切换为展开(完全显示),然后再返回。

起初我尝试直接为 max-height 属性设置动画,正如您在上面发现的那样,这是行不通的。我也用 css transitions 尝试过这个,结果同样令人失望。

我也试过将它设置为一个非常大的数字,比如“1000em”,但这让动画看起来很愚蠢,因为它实际上是插值到如此大的值(如您所料)。

我的解决方案使用 scrollHeight,它用于在页面加载后确定每个故事的自然高度,如下所示:

$(function(){ // DOM LOADED

  // For each story, determine its natural height and store it as data.
  // This is encapsulated into a self-executing function to isolate the 
  // variables from other things in my script.
  (function(){

    // First I grab the collapsed height that was set in the css for later use
    var collapsedHeight = $('article .story').css('maxHeight');

    // Now for each story, grab the scrollHeight property and store it as data 'natural'        
    $('article .story').each(function(){
      var $this = $(this);

      $this.data('natural', $this[0].scrollHeight);
    });

    // Now, set-up the handler for the toggle buttons
    $('.expand').bind('click', function(){
      var $story = $(this).parent().siblings('.story').eq(0),
          duration = 250; // animation duration

      // I use a class 'expanded' as a flag to know what state it is in,
      // and to make style changes, as required.  
      if ($story.hasClass('expanded')) {
        // If it is already expanded, then collapse it using the css figure as
        // collected above and remove the expanded class
        $story.animate({'maxHeight': collapsedHeight}, duration);
        $story.removeClass('expanded');
      }
      else {
        // If it is not expanded now, then animate the max-height to the natural
        // height as stored in data, then add the 'expanded' class
        $story.animate({'maxHeight': $story.data('natural')}, duration);
        $story.addClass('expanded');
      }
    });

  })(); // end anonymous, self-executing function

});

要对图像做同样的事情,我会将它们包裹在一个外部 div 中,您将在其中设置 max-heightoverflow:hidden,就像我在上面使用的 div.story 一样。

关于jquery - 在 jQuery 中,如何为 "max-height"CSS 属性设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3569379/

相关文章:

javascript - 用 JavaScript 模拟非洲村庄的分形

javascript - 使用 javascript 或 jQuery 摆脱 div 元素中的某些特定文本

jquery - css jquery 菜单 - 切换幻灯片放映隐藏 div

html - 在元素之前使用 <i> 而不是将元素包装在 <span> 中有什么好处?

php - 如何将页脚中回显的 <div> float 到位于其他位置的 <div> 上 (PHP/jQuery/HTML/CSS)

jQuery - 随机化框并在窗口加载时为它们设置动画

jquery - 获取接下来的 6 个结果

javascript - jquery 将对象从底部移动到顶部

javascript - jQuery 动画在 Firefox 中断断续续

javascript - .animate() 不工作?