使用jQuery将元素动画化为自动高度

Dan*_*iel 166 html javascript css jquery jquery-animate

我想要动画<div>从高200pxauto高.我似乎无法让它工作.有谁知道怎么样?

这是代码:

$("div:first").click(function(){
  $("#first").animate({
    height: "auto"
  }, 1000 );
});
Run Code Online (Sandbox Code Playgroud)

Dav*_*ang 246

  1. 保存当前高度:

    var curHeight = $('#first').height();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 暂时将高度切换为自动:

    $('#first').css('height', 'auto');
    
    Run Code Online (Sandbox Code Playgroud)
  3. 获得自动高度:

    var autoHeight = $('#first').height();
    
    Run Code Online (Sandbox Code Playgroud)
  4. 切换回curHeight动画autoHeight:

    $('#first').height(curHeight).animate({height: autoHeight}, 1000);
    
    Run Code Online (Sandbox Code Playgroud)

和在一起:

var el = $('#first'),
    curHeight = el.height(),
    autoHeight = el.css('height', 'auto').height();
el.height(curHeight).animate({height: autoHeight}, 1000);
Run Code Online (Sandbox Code Playgroud)

  • 这是有效的,但我添加了一个回调,它将自动增长行为恢复为元素`.animated({height:autoHeight},1000,function(){el.height('auto');}); (21认同)
  • 这有可能导致FOUC.在动画制作之前,用户可能会看到元素在瞬间跳转到全高. (4认同)

Liq*_*aut 186

IMO这是最干净,最简单的解决方案:

$("#first").animate({height: $("#first").get(0).scrollHeight}, 1000 );
Run Code Online (Sandbox Code Playgroud)

说明:DOM已经从其初始渲染中知道扩展div在设置为自动高度时将具有的大小.此属性存储在DOM节点中scrollHeight.我们只需通过调用从jQuery元素中获取DOM元素get(0),然后我们就可以访问该属性.

添加回调函数将高度设置为auto可以在动画完成后提供更高的响应能力(credit chris-williams):

$('#first').animate({
    height: $('#first').get(0).scrollHeight
}, 1000, function(){
    $(this).height('auto');
});
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案,因为它在没有任何闪烁的情况下效果最佳,并且确实能够很好地完成工作 (22认同)
  • 我也认为这是最好的解决方案.我会添加一个回调函数来将高度设置为auto以获得更高的响应性.`$('#first').animate({height:$('#first').get(0).scrollHeight},1000,function(){$(this).height('auto');}) ;` (7认同)
  • 惊人!根据https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollHeight,它甚至在IE8中得到支持,而`clientHeight`似乎不受支持:https://developer.mozilla .ORG/EN-US /文档/网络/ API/Element.clientHeight (2认同)
  • 哇,这太优雅了。它还可以与“scrollWidth”一起使用来实现宽度动画。 (2认同)

小智 24

这与Box9的答案基本相同,但是我将它包装在一个漂亮的jquery插件中,插件采用与常规动画相同的参数,因为当你需要有更多的动画参数并厌倦了反复重复相同的代码时:

;(function($)
{
  $.fn.animateToAutoHeight = function(){
  var curHeight = this.css('height'),
      height = this.css('height','auto').height(),
      duration = 200,
      easing = 'swing',
      callback = $.noop,
      parameters = { height: height };
  this.css('height', curHeight);
  for (var i in arguments) {
    switch (typeof arguments[i]) {
      case 'object':
        parameters = arguments[i];
        parameters.height = height;
        break;
      case 'string':
        if (arguments[i] == 'slow' || arguments[i] == 'fast') duration = arguments[i];
        else easing = arguments[i];
        break;
      case 'number': duration = arguments[i]; break;
      case 'function': callback = arguments[i]; break;
    }
  }
  this.animate(parameters, duration, easing, function() {
    $(this).css('height', 'auto');
    callback.call(this, arguments);
  });
  return this;
  }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

编辑:现在可链接和清洁


Tim*_*ler 23

更好的解决方案不依赖于JS来设置元素的高度.以下是将固定高度元素设置为完整("自动")高度的解决方案:

var $selector = $('div');
    $selector
        .data('oHeight',$selector.height())
        .css('height','auto')
        .data('nHeight',$selector.height())
        .height($selector.data('oHeight'))
        .animate({height: $selector.data('nHeight')},400);
Run Code Online (Sandbox Code Playgroud)

https://gist.github.com/2023150

  • 这个oneliner不容易理解,也许写几行可以帮助其他人更好一点. (2认同)

czL*_*sss 11

这是有效的,它比以前的解决方案更简单:

CSS:

#container{
  height:143px;  
}

.max{
  height: auto;
  min-height: 143px;
}
Run Code Online (Sandbox Code Playgroud)

JS:

$(document).ready(function() {
    $("#container").click(function() {      
        if($(this).hasClass("max")) {
            $(this).removeClass("max");
        } else {
            $(this).addClass("max");
        }

    })
});
Run Code Online (Sandbox Code Playgroud)

注意:此解决方案需要jQuery UI

  • 你也可以使用$(this).toggleClass('max',250); 而不是使用if语句 (4认同)

小智 9

var h = document.getElementById('First').scrollHeight;
$('#First').animate({ height : h+'px' },300);
Run Code Online (Sandbox Code Playgroud)


小智 7

您始终可以将#first的子元素包装起来,并将包装器的高度保存为变量.这可能不是最漂亮或最有效的答案,但它可以解决问题.

这是一个小提琴,其中包括重置.

但为了你的目的,这里的肉和土豆:

$(function(){
//wrap everything inside #first
$('#first').children().wrapAll('<div class="wrapper"></div>');
//get the height of the wrapper 
var expandedHeight = $('.wrapper').height();
//get the height of first (set to 200px however you choose)
var collapsedHeight = $('#first').height();
//when you click the element of your choice (a button in my case) #first will animate to height auto
$('button').click(function(){
    $("#first").animate({
        height: expandedHeight            
    })
});
});?
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 5

我设法解决了它:D继承代码.

var divh = document.getElementById('first').offsetHeight;
$("#first").css('height', '100px');
$("div:first").click(function() {
  $("#first").animate({
    height: divh
  }, 1000);
});
Run Code Online (Sandbox Code Playgroud)


Ron*_*rer 5

使用slideDownslideUp

$("div:first").click(function(){ $("#first").slideDown(1000); });
Run Code Online (Sandbox Code Playgroud)


EMM*_*ICH 3

您的选择器似乎不匹配。您的元素的 ID 是否为“first”,或者它是每个 div 中的第一个元素?

更安全的解决方案是使用“this”:

// assuming the div you want to animate has an ID of first
$('#first').click(function() {
  $(this).animate({ height : 'auto' }, 1000);
});
Run Code Online (Sandbox Code Playgroud)

  • `animate({height: 'auto'})` 没有任何效果。至少 jQuery 1.6.4 不是这样。 (12认同)