jQuery를 사용하여 요소를 자동 높이로 애니메이션 200px에 auto높이입니다. 그래도 작동하지 않는 것

나는 애니메이션을 할 <div>에서 200pxauto높이입니다. 그래도 작동하지 않는 것 같습니다. 아무도 방법을 알고 있습니까?

코드는 다음과 같습니다.

$("div:first").click(function(){
  $("#first").animate({
    height: "auto"
  }, 1000 );
});


답변

  1. 현재 높이를 저장하십시오.

    var curHeight = $('#first').height();
  2. 일시적으로 높이를 자동으로 전환하십시오.

    $('#first').css('height', 'auto');
  3. 자동 높이를 가져옵니다.

    var autoHeight = $('#first').height();
  4. 다음으로 전환 curHeight하여 애니메이션을 적용하십시오 autoHeight.

    $('#first').height(curHeight).animate({height: autoHeight}, 1000);

그리고 함께 :

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

답변

IMO는 가장 깨끗하고 쉬운 솔루션입니다.

$("#first").animate({height: $("#first").get(0).scrollHeight}, 1000 );

설명 : DOM은 초기 렌더링에서 이미 자동 높이로 설정했을 때 확장 된 div의 크기를 알고 있습니다. 이 속성은 DOM 노드에로 저장됩니다 scrollHeight. 호출하여 jQuery 요소에서 DOM 요소를 가져와야 get(0)속성에 액세스 할 수 있습니다.

높이를 자동으로 설정하기 위해 콜백 함수를 추가하면 애니메이션이 완료된 후 응답 성이 향상됩니다 (신용 chris-williams ).

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

답변

이것은 기본적으로 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);

편집 : 체인 가능하고 깔끔한 지금


답변

더 나은 솔루션은 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);

https://gist.github.com/2023150


답변

이것은 작동하고 전에 솔루션보다 간단합니다.

CSS :

#container{
  height:143px;
}

.max{
  height: auto;
  min-height: 143px;
}

JS :

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

    })
});

참고 :이 솔루션에는 jQuery UI가 필요합니다


답변

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

답변

항상 #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
    })
});
});​