Вопрос

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

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

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

.... 

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

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

Мысли?

Это было полезно?

Решение

Попробуйте этот плагин 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(), и прохождение true для второго(перейти к концу) параметр:

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

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

Другие советы

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

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

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

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

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

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

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

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

Привет, meyahoocoma4c5ki0pprxr19sxhajsogo6jgks5dt.

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

Вы можете сгладить анимацию jQuery, используя dequeue.Проверьте наличие класса (устанавливается при наведении курсора и удаляется при обратном вызове анимации 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 приведет к анимации переключения ширины остальных трех и переместит выбранный элемент в крайнее левое положение.

enter image description here

enter image description here

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top