Подтвердить что ты не робот

JQuery Animation - плавный переход по размеру

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

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

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

.... 

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

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

Мысли?

4b9b3361

Ответ 1

Попробуйте этот плагин 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 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() и передать true для второго (jumpToEnd ):

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

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

Ответ 2

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

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

Ответ 3

может быть что-то вроде этого?

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

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

Ответ 4

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

Может быть более короткая версия моего кода, но я просто сохранил ее так.

Ответ 5

Это делает работу для меня. Вы также можете добавить ширину к временному 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();
  });
});

Ответ 6

Привет meyahoocoma4c5ki0pprxr19sxhajsogo6jgks5dt.

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

Ответ 7

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

Вот быстрая демонстрация

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

Ответ 8

Чтобы создать обратную связь в редакторе jquery plugin (слишком низкая репутация, чтобы добавить это как комментарий), jQuery.html() удалит любые обработчики событий на добавленном html. Изменение:

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

to

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

сохранит обработчики событий элементов "html"