jQuery Animation - Плавный переход по размеру - PullRequest
33 голосов
/ 28 октября 2008

Так что это может быть очень просто, но я пока не смог найти примеров, на которых можно было бы поучиться, поэтому, пожалуйста, потерпите меня. ;)

Вот в основном то, что я хочу сделать:

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

.... 

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

Я хочу плавно анимировать между измерениями div с большим количеством контента к измерениям div с очень небольшим, когда вводится новое содержимое.

Мысли

Ответы [ 8 ]

47 голосов
/ 29 октября 2008

Попробуйте этот плагин 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);

Commenter RonLugge указывает, что это может вызвать проблемы, если дважды вызвать его для одного и того же элемента (ов), когда первая анимация не закончилась до начала второй. Это связано с тем, что вторая анимация примет текущие (средние анимации) размеры в качестве желаемых «конечных» значений и продолжит фиксировать их как конечные значения (эффективно останавливая анимацию в ее дорожках, а не анимируя в направлении «естественного» размера ) ...

Самый простой способ решить эту проблему - вызвать stop() перед вызовом showHtml() и передать true для второго ( jumpToEnd ) параметра:

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

Это приведет к немедленному завершению первой анимации (если она все еще запущена) до начала новой.

42 голосов
/ 29 октября 2008

Вы можете использовать одушевленный метод .

$("div").animate({width:"200px"},400);
6 голосов
/ 24 января 2009

Вот как я это исправил, надеюсь, это будет полезно! Анимация плавная на 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);
    });
});

Возможно, у меня более короткая версия кода, но я просто сохранил ее так.

6 голосов
/ 28 октября 2008

может быть как то так?

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

Близко к тому, что, я думаю, вы хотели, также попробуйте slideIn / slideOut или посмотрите на плагин UI / Effects.

1 голос
/ 12 мая 2011

Это делает работу для меня. Вы также можете добавить ширину к временному разделителю.

$('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();
  });
});
0 голосов
/ 17 декабря 2014

Чтобы добавить решение для плагина 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"

0 голосов
/ 26 ноября 2014

Вы можете сгладить анимацию jQuery, используя dequeue. Проверьте наличие класса (установленный при наведении и удаленный при обратном вызове mouseOut animate) перед началом новой анимации. Когда новая анимация начнется, удалите очередь.

Вот небольшая демонстрация.

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 и перемещается элемент, на который щелкают, в крайнее левое положение.

enter image description here

enter image description here

0 голосов
/ 29 октября 2008

Здравствуйте, meyahoocoma4c5ki0pprxr19sxhajsogo6jgks5dt.

Вы можете обернуть 'div содержимого' 'внешним div', для которого установлено абсолютное значение ширины. Вставьте новое содержимое методом «hide ()» или «animate ({width})», как показано в других ответах. Таким образом, страница не переворачивается между ними, потому что div-обертка имеет постоянную ширину.

...