Pergunta

Então, isso pode ser muito simples, mas eu não tenho sido capaz de encontrar qualquer exemplos para aprender fora ainda, por isso, tenha comigo. ;)

Aqui é basicamente o que eu quero fazer:

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

.... 

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

Eu quero suavemente animar entre as dimensões da div com lotes de conteúdo para as dimensões da div com muito pouco quando o novo conteúdo é injetado.

Os pensamentos?

Foi útil?

Solução

Tente este plugin 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 aponta que isso pode causar problemas se você chamá-lo duas vezes no mesmo elemento (s), onde a primeira animação não terminou antes da segunda começa. Isso ocorre porque a segunda animação levará a corrente (meados de animação) tamanhos, os valores desejados "Ending", e proceder para corrigi-los como os valores finais (parar efetivamente a animação em suas faixas ao invés de animação para o tamanho "natural" ) ...

A maneira mais fácil de resolver isso é para chamar stop() antes de chamar showHtml(), e passando true para o segundo ( jumpToEnd ) parâmetro:

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

Isto fará com que a primeira animação para concluir imediatamente (se ele ainda está em execução), antes de iniciar um novo.

Outras dicas

Você pode usar o animado método .

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

talvez algo como isso?

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

Fechar para que eu acho que você queria, também tentar slideIn / SlideOut ou olhar para o UI / Efeitos plugin.

Aqui está como eu reparei isso, espero que isso vai ser útil! A animação é 100% suavizar:)

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

Pode haver uma versão mais curta do meu código, mas eu continuei assim.

Este faz o trabalho para mim. Você também pode adicionar uma largura para o div temporário.

$('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();
  });
});

Olá meyahoocoma4c5ki0pprxr19sxhajsogo6jgks5dt.

Você poderia envolver o 'div conteúdo' com um 'div externa', que é definido para um valor de largura absoluta. Inject o novo conteúdo com um "hide ()" ou "animado ({width})" método, mostrado em outras respostas. Desta forma, a página não refluir entre porque o div capa tem uma largura constante.

Você pode suavizar a animação jQuery usando dequeue. Teste para a presença de classe (definido em cima pairar e removido em mouseOut animado de retorno de chamada) antes de iniciar nova animação. Quando nova animação for iniciado, dequeue.

Aqui está uma demonstração rápida.

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');
    });
});

A demonstração é configurado como 5 colunas de altura completa, clicando em qualquer uma das colunas 2 através de 5 animará alternância largura da outra 3 e mover o elemento clicado para a extrema esquerda.

enter descrição da imagem aqui

enter descrição da imagem aqui

Para piggy-back sobre o plugin jQuery solução (muito baixo de reputação para adicionar este como um comentário) jQuery.html () irá remover quaisquer manipuladores de eventos no html anexado. Alterar:

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

para

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

reterá os manipuladores de eventos das "HTML" elementos

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top