在 jQuery.load() 上对容器的高度进行动画处理

2024-03-14

我正在使用 $('#container_div').load(url) 通过 ajax 填充 div。我想将高度设置为返回内容的高度,但真的不知道如何实现这一点。

我尝试过使用这样的东西:

$('#main').fadeOut(function() {

 $('#main').load(url, function(data) {
     var newHeight = $(data).height();
        $('#main').animate({height:newHeight}, function() {$('#main').fadeIn();});
     });
 });

但可以看出,这在很多层面上都是错误的。特别是因为 newHeight === 未定义。

有人能在这里指出正确的方向吗?我将永远感激不已。


Since 消退() http://api.jquery.com/fadeOut/通过隐藏目标元素来完成,很可能在加载新数据时您的 #main 将完全隐藏,从而使任何高度的动画不可见,因此毫无意义。

But you could只需使用类似的东西$('#main').show(400) http://api.jquery.com/show/这将使元素从大小 (0,0) 和不透明度 0 动画到容器和内容允许的任何大小以及完全可见的不透明度 1(并并行运行这些动画,使它们都可见) 。

但是假设您确实更关心高度动画而不是淡入淡出,那么您仍然遇到一个问题:当 load() 调用其回调时,目标元素的高度已经be内容的高度(或尽可能接近它)。所以动画不会做任何事情。

我在上一个问题上发布了一个插件 https://stackoverflow.com/questions/244758/jquery-animation-smooth-size-transition这将做你想做的事,但你需要使用$.get() http://api.jquery.com/jQuery.get/代替load() http://api.jquery.com/load/:

$.get(url, function(data) {
  $('#main').showHtml(data);
});

...其中 showHtml 定义为:

// Animates the dimensional changes resulting from altering element contents
// Usage examples: 
//    $("#myElement").showHtml("new HTML contents");
//    $("div").showHtml("new HTML contents", 400);
//    $(".className").showHtml("new HTML contents", 400, 
//                    function() {/* on completion */});
(function($)
{
   $.fn.showHtml = function(html, speed, callback)
   {
      return this.each(function()
      {
         // The element to be modified
         var el = $(this);

         // Preserve the original values of width and height - they'll need 
         // to be modified during the animation, but can be restored once
         // the animation has completed.
         var finish = {width: this.style.width, height: this.style.height};

         // The original width and height represented as pixel values.
         // These will only be the same as `finish` if this element had its
         // dimensions specified explicitly and in pixels. Of course, if that 
         // was done then this entire routine is pointless, as the dimensions 
         // won't change when the content is changed.
         var cur = {width: el.width()+'px', height: el.height()+'px'};

         // Modify the element's contents. Element will resize.
         el.html(html);

         // Capture the final dimensions of the element 
         // (with initial style settings still in effect)
         var next = {width: el.width()+'px', height: el.height()+'px'};

         el .css(cur) // restore initial dimensions
            .animate(next, speed, function()  // animate to final dimensions
            {
               el.css(finish); // restore initial style settings
               if ( $.isFunction(callback) ) callback();
            });
      });
   };


})(jQuery);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 jQuery.load() 上对容器的高度进行动画处理 的相关文章

随机推荐