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

Tim*_*uri 12 css jquery jquery-animate

我可以很容易地为"不透明"属性设置动画

$("#blah").animate({ opacity: 0.5}, 1000);
Run Code Online (Sandbox Code Playgroud)

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

$("#blah").animate({ "max-height": 350}, 1000);
Run Code Online (Sandbox Code Playgroud)

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

编辑:回答以下问题:

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

mko*_*nen 9

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

就我而言,我有这首先呈现的页面与博客文章列表max-height只显示前4行文字,其余为overflow: hidden.我有一个展开/折叠按钮,可以将文章从折叠形式切换为展开(完全显示)并再次返回.

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

我也尝试将它设置为一个非常大的数字,如'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

});
Run Code Online (Sandbox Code Playgroud)

要做到与图像一样,我只想将它们包装在外层div这是什么,你会设置max-heightoverflow:hidden上,就像我上面使用div.story.


rfo*_*nal 5

我遇到了同样的事情。

答案是使用"maxHeight"而不是"max-height"...

  • `maxHeight` 和 `"max-height"` 都可以在较新版本的 jQuery 中使用。http://jsfiddle.net/9jswu7L6/1/ (2认同)

Tim*_*uri 0

好吧,所以没有办法做我想做的事......所以我不得不让自己的函数具有通用的“动画”函数(从 x 到 y 在 d 毫秒内)。

我写了一篇博客文章描述我是如何做到这一点的:Generic "Animate" function with jQuery

我还提供了一个演示,展示了它的功能。演示链接位于文章底部,或者如果没有耐心,您可以点击这里