문제

그래서 이것은 정말 간단 할 수도 있지만 아직 배울 수있는 사례를 찾을 수 없었습니다. ;)

기본적으로 내가하고 싶은 일은 다음과 같습니다.

<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 두 번째 (Jumptoend) 매개 변수 :

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

내가 원한다고 생각하는 것과 가까이, SlideIn/Slideout을 시도하거나 UI/Effects 플러그인을보십시오.

여기에 내가 이것을 수정하는 방법은 다음과 같습니다. 이것이 유용하기를 바랍니다. 애니메이션은 100% 부드럽습니다 :)

HTML :

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

자바 스크립트 :

// 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.

'Content Div'를 '외부 div'로 래핑하는 '외부 div'로 랩핑 할 수있는 절대 너비 값으로 설정 될 수 있습니다. 다른 답변에 표시된 "hide ()"또는 "animate ({width})"메소드로 새 콘텐츠를 주입하십시오. 이런 식으로, 래퍼 디바리가 꾸준한 너비를 유지하기 때문에 페이지는 사이에 반사되지 않습니다.

jQuery 애니메이션을 사용하여 부드럽게 할 수 있습니다 dequeue. 새로운 애니메이션을 쳐다보기 전에 클래스의 존재를 테스트하고 마우스 아웃 애니메이션 콜백에서 제거 됨). 새로운 애니메이션이 시작되면 Dequeue.

다음은 빠른 데모입니다.

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

jQuery 플러그인 솔루션에서 Piggy-Back (이를 주석으로 추가하기에는 평판이 너무 낮습니다) 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