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

IT技术 javascript jquery html css jquery-animate
2021-01-18 18:46:08

我想<div>200pxauto高度动画我似乎无法让它工作。有谁知道怎么做?

这是代码:

$("div:first").click(function(){
  $("#first").animate({
    height: "auto"
  }, 1000 );
});
6个回答
  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);
这有可能导致 FOUC。用户可能会在动画之前看到元素跳到全高的一瞬间。
2021-03-25 18:46:08
您可以通过opacity: 0; position: absolute;在测量时最初提供元素并在完成后删除这些元素来防止 FOUC(“无样式内容的flash”)
2021-03-25 18:46:08
@Daniel,你的 JS 代码在哪里?发布那一点,以及显示您引用的元素的 HTML 部分。
2021-03-29 18:46:08
这有效,但我添加了一个回调来恢复元素的自动增长行为 .animated({height: autoHeight}, 1000, function(){ el.height('auto'); });
2021-03-31 18:46:08
在响应式设计上设置固定高度时要小心。如果用户调整屏幕大小,它就会变得一团糟。动画完成后,最好将高度设置为“自动”。
2021-04-03 18:46:08

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

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

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

添加回调函数以将高度设置为 auto 可在动画完成后提高响应速度(信用chris-williams):

$('#first').animate({
    height: $('#first').get(0).scrollHeight
}, 1000, function(){
    $(this).height('auto');
});
边距是根据盒子模型的定义而不是对象高度的一部分。不过,您始终可以自己添加边距。
2021-03-20 18:46:08
惊人!根据developer.mozilla.org/en-US/docs/Web/API/Element.scrollHeight它甚至在 IE8 中得到支持,相比之下clientHeight,似乎不受支持:developer.mozilla.org/en-US/docs/Web/ API/Element.clientHeight
2021-03-26 18:46:08
这应该是公认的答案,因为它在没有任何闪烁的情况下效果最好,并且确实可以很好地完成工作
2021-03-26 18:46:08
哇,这个超级优雅。它也适用scrollWidth于宽度动画。
2021-03-29 18:46:08
我也认为这是最好的解决方案。我会添加一个回调函数来将高度设置为自动以获得更多响应。 $('#first').animate({ height: $('#first').get(0).scrollHeight }, 1000, function() { $(this).height('auto'); });
2021-03-30 18:46:08

这基本上与 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

这个oneliner不好理解,也许多写几行会帮到别人好一点。
2021-03-19 18:46:08
这是最好的解决方案,因为如果用户调整窗口大小,自动高度可能会改变。请参阅以下内容: //动画过滤器的高度函数toggleSlider(){ if ($('#filters').height() != 0) { $('#filters').animate({height:'0 '}); } else{ var $selector = $('#filters'); $selector .data('oHeight',$selector.height()) .css('height','auto') .data('nHeight',$selector.height()) .height($selector.data(' oHeight')) .animate({height: $selector.data('nHeight')},400); }; console.log('agg'); }
2021-03-22 18:46:08
有效,但这设置height为固定值(例如 122px)。一段时间后我的元素改变了高度,所以我不得不用选项替换持续时间参数(400){duration: 400, complete: function() {$selector.css('height', 'auto');}}
2021-03-24 18:46:08
可以使 div 打开,但动画不超过 400 毫秒。也许我有其他不同的设置,但它只是眨眼间打开。
2021-04-10 18:46:08

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

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

你也可以使用 $(this).toggleClass('max', 250); 而不是使用 if 语句
2021-03-28 18:46:08
为什么你在.addClassand 中包含第二个值.removeClass
2021-04-06 18:46:08
应该提到的是,这需要 Jquery UI 插件,而最初的问题仅是关于 jquery。但是如果您使用的是 Jquery UI,它就可以工作。
2021-04-07 18:46:08