jQuery 动画 - 平滑大小过渡

发布于 2024-07-08 13:14:53 字数 297 浏览 9 评论 0原文

所以这可能非常简单,但我还没有找到任何可以学习的例子,所以请耐心等待。 ;)

这基本上就是我想要做的:

<div>Lots of content! Lots of content! Lots of content! ...</div>

.... 

$("div").html("Itsy-bitsy bit of content!");

当注入新内容时,我希望在内容较多的 div 尺寸和内容很少的 div 尺寸之间平滑地进行动画处理。

想法?

So this might be really simple, but I haven't been able to find any examples to learn off of yet, so please bear with me. ;)

Here's basically what I want to do:

<div>Lots of content! Lots of content! Lots of content! ...</div>

.... 

$("div").html("Itsy-bitsy bit of content!");

I want to smoothly animate between the dimensions of the div with lots of content to the dimensions of the div with very little when the new content is injected.

Thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

最丧也最甜 2024-07-15 13:14:54

这对我来说很有效。 您还可以为临时 div 添加宽度。

$('div#to-transition').wrap( '<div id="tmp"></div>' );
$('div#tmp').css( { height: $('div#to-transition').outerHeight() + 'px' } );
$('div#to-transition').fadeOut('fast', function() {
  $(this).html(new_html);
  $('div#tmp').animate( { height: $(this).outerHeight() + 'px' }, 'fast' );
  $(this).fadeIn('fast', function() {
    $(this).unwrap();
  });
});

This does the job for me. You can also add a width to the temp div.

$('div#to-transition').wrap( '<div id="tmp"></div>' );
$('div#tmp').css( { height: $('div#to-transition').outerHeight() + 'px' } );
$('div#to-transition').fadeOut('fast', function() {
  $(this).html(new_html);
  $('div#tmp').animate( { height: $(this).outerHeight() + 'px' }, 'fast' );
  $(this).fadeIn('fast', function() {
    $(this).unwrap();
  });
});
一抹淡然 2024-07-15 13:14:54

你好,meyahoocoma4c5ki0pprxr19sxhajsogo6jgks5dt。

您可以使用设置为绝对宽度值的“外部 div”包裹“内容 div”。 使用“hide()”或“animate({width})”方法注入新内容,如其他答案所示。 这样,页面就不会在中间回流,因为包装器 div 保持稳定的宽度。

Hello meyahoocoma4c5ki0pprxr19sxhajsogo6jgks5dt.

You could wrap the 'content div' with an 'outer div' which is set to an absolute width value. Inject the new content with a "hide()" or "animate({width})" method, shown in the other answers. This way, the page doesn't reflow in between because the wrapper div holds a steady width.

岁月静好 2024-07-15 13:14:54

您可以使用 dequeue 平滑 jQuery 动画。 在开始新动画之前测试类的存在(在悬停时设置并在 mouseOut 动画回调中删除)。 当新动画开始时,出队。

这是一个快速演示。

var space = ($(window).width() - 100);
$('.column').width(space/4);

$(".column").click(function(){
    if (!$(this).hasClass('animated')) {
        $('.column').not($(this).parent()).dequeue().stop().animate({width: 'toggle', opacity: '0.75'}, 1750,'linear', function () {});
    }

  $(this).addClass('animated');
    $('.column').not($(this).parent()).dequeue().stop().animate({width: 'toggle', opacity: '0.75'}, 1750,'linear', function () {
          $(this).removeClass('animated').dequeue();

      });
    $(this).dequeue().stop().animate({
        width:(space/4)
    }, 1400,'linear',function(){
      $(this).html('AGAIN');
    });
});

该演示设置为 5 个全高列,单击任意第 2 列到第 5 列将为其他 3 列的切换宽度设置动画,并将单击的元素移动到最左侧。

在此处输入图像描述

在此输入图像描述

You can smooth out the jQuery animation using dequeue. Test for presence of class (set upon hover and removed on mouseOut animate callback) before staring new animation. When new animation does start, dequeue.

Here's a quick demo.

var space = ($(window).width() - 100);
$('.column').width(space/4);

$(".column").click(function(){
    if (!$(this).hasClass('animated')) {
        $('.column').not($(this).parent()).dequeue().stop().animate({width: 'toggle', opacity: '0.75'}, 1750,'linear', function () {});
    }

  $(this).addClass('animated');
    $('.column').not($(this).parent()).dequeue().stop().animate({width: 'toggle', opacity: '0.75'}, 1750,'linear', function () {
          $(this).removeClass('animated').dequeue();

      });
    $(this).dequeue().stop().animate({
        width:(space/4)
    }, 1400,'linear',function(){
      $(this).html('AGAIN');
    });
});

The demo is setup as 5 full-height columns, clicking any of the columns 2 thru 5 will animate toggle width of the other 3 and move the clicked element to the far left.

enter image description here

enter image description here

千と千尋 2024-07-15 13:14:54

为了搭载 jquery 插件解决方案(声誉太低,无法将其添加为评论),jQuery.html() 将删除附加 html 上的任何事件处理程序。 更改:

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

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

保留“html”元素的事件处理程序

To piggy-back on the jquery plugin solution (too low of reputation to add this as a comment) jQuery.html() will remove any event handlers on the appended html. Changing:

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

to

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

will retain the event handlers of the "html" elements

王权女流氓 2024-07-15 13:14:53

尝试这个 jQuery 插件:

// 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);

评论者 RonLugge 指出,如果您在同一个元素上调用它两次,这可能会导致问题,其中第一个动画在第二个动画开始之前尚未完成。 这是因为第二个动画将把当前(动画中间)大小作为所需的“结束”值,并继续将它们修复为最终值(有效地停止动画的轨道,而不是朝着“自然”大小进行动画处理) )...

解决此问题的最简单方法是调用 stop() 在调用 showHtml() 之前,并为第二个 (jumpToEnd) 参数传递 true 之前:

$(selector).showHtml("new HTML contents")
           .stop(true, true)
           .showHtml("even newer contents");

这将导致第一个动画立即完成(如果它仍在运行),然后开始新的一个。

Try this jQuery plugin:

// 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);

Commenter RonLugge points out that this can cause problems if you call it twice on the same element(s), where the first animation hasn't finished before the second begins. This is because the second animation will take the current (mid-animation) sizes as the desired "ending" values, and proceed to fix them as the final values (effectively stopping the animation in its tracks rather than animating toward the "natural" size)...

The easiest way to resolve this is to call stop() before calling showHtml(), and passing true for the second (jumpToEnd) parameter:

$(selector).showHtml("new HTML contents")
           .stop(true, true)
           .showHtml("even newer contents");

This will cause the first animation to complete immediately (if it is still running), before beginning a new one.

花想c 2024-07-15 13:14:53

您可以使用动画方法

$("div").animate({width:"200px"},400);

You can use the animate method.

$("div").animate({width:"200px"},400);
不羁少年 2024-07-15 13:14:53

也许是这样的?

$(".testLink").click(function(event) {
    event.preventDefault();
    $(".testDiv").hide(400,function(event) {
        $(this).html("Itsy-bitsy bit of content!").show(400);
    });
});

接近我认为你想要的,也尝试slideIn/slideOut 或查看 UI/Effects 插件。

maybe something like this?

$(".testLink").click(function(event) {
    event.preventDefault();
    $(".testDiv").hide(400,function(event) {
        $(this).html("Itsy-bitsy bit of content!").show(400);
    });
});

Close to what I think you wanted, also try slideIn/slideOut or look at the UI/Effects plugin.

小姐丶请自重 2024-07-15 13:14:53

这是我解决这个问题的方法,我希望这会有用!
动画 100% 流畅:)

HTML:

<div id="div-1"><div id="div-2">Some content here</div></div>

Javascript:

// cache selectors for better performance
var container = $('#div-1'),
    wrapper = $('#div-2');

// temporarily fix the outer div's width
container.css({width: wrapper.width()});
// fade opacity of inner div - use opacity because we cannot get the width or height of an element with display set to none
wrapper.fadeTo('slow', 0, function(){
    // change the div content
    container.html("<div id=\"2\" style=\"display: none;\">new content (with a new width)</div>");
    // give the outer div the same width as the inner div with a smooth animation
    container.animate({width: wrapper.width()}, function(){
        // show the inner div
        wrapper.fadeTo('slow', 1);
    });
});

我的代码可能有一个较短的版本,但我只是保持这样。

Here is how I fixed this, I hope this will be usefull !
The animation is 100% smooth :)

HTML:

<div id="div-1"><div id="div-2">Some content here</div></div>

Javascript:

// cache selectors for better performance
var container = $('#div-1'),
    wrapper = $('#div-2');

// temporarily fix the outer div's width
container.css({width: wrapper.width()});
// fade opacity of inner div - use opacity because we cannot get the width or height of an element with display set to none
wrapper.fadeTo('slow', 0, function(){
    // change the div content
    container.html("<div id=\"2\" style=\"display: none;\">new content (with a new width)</div>");
    // give the outer div the same width as the inner div with a smooth animation
    container.animate({width: wrapper.width()}, function(){
        // show the inner div
        wrapper.fadeTo('slow', 1);
    });
});

There might be a shorter version of my code, but I just kept it like this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文