2011-12-14 6 views
2

안녕하세요, 저는 프로그래밍 jQuery에 익숙하지 않습니다. 빠른 코드 스 니펫을 사용하여 나를 테스트 해줄 사람을 사랑합니다.jQuery : 슬라이드 토글 || 코드 최적화?

나는 그것이 잘 작동한다고 생각한다. 그러나 나는 그것을 다루는 가장 좋은 방법인지는 모른다.

작업 예 : 여기 http://jsfiddle.net/zWnLv/29/

//hide wrapper at document ready 
     $('#newsbox_content_wrapper').hide(); 

     //toggle visiblility of newsbox and slide down to scroll window to newsbox 
     $('.newsbox_toggle').bind('click', function() { 
      //define speed for effect 
      var $speed = 400; 

      //check to see if the class 'open' exists then run 
      if ($('.newsbox_toggle').hasClass('open')) { 
       //scroll to the top of the newsbox 
       $('html, body').animate({scrollTop: $('#header_lower').offset().top}, $speed); 
       $('#newsbox_content_wrapper').slideDown($speed); 
       $('.newsbox_toggle').removeClass('open'); 
       //delay HTML replacement to sync with animation 
       $('.newsbox_expand').delay($speed).queue(function(n) { 
        $(this).html('Click to Close News Feature.'); 
        $(this).addClass('rotate'); 
        n(); 
       }); 
      } else { 
       //scroll back to top of body 
       $('html, body').animate({ scrollTop: 0 }, $speed); 
       $('#newsbox_content_wrapper').slideUp($speed); 
       $('.newsbox_toggle').addClass('open'); 
       //delay HTML replacement to sync with animation 
       $('.newsbox_expand').delay($speed).queue(function(n) { 
        $(this).html('Click to Read More.'); 
        $(this).removeClass('rotate'); 
        n(); 
       }); 
      } 
     }); 

답변

2

"최적화"할 수있는 유일한 방법은 수동으로 함수를 지연시키는 대신 콜백을 사용하는 것입니다. .slideUp().slideDown()은 애니메이션이 끝난 후에 실행될 콜백을 허용합니다. 체인 사용은 모범 사례이므로 개체를 다시 만들 필요가 없습니다 (콜백 함수 참조).

또한 bind() 함수를 새로운 on()으로 변경했습니다.이 함수는 jQuery 1.7에 추가되었습니다. 당신이 jQuery를 < 1.7에 경우

$('.newsbox_toggle').on('click', function() { 
    //define speed for effect 
    var $speed = 400; 

    //check to see if the class 'open' exists then run 
    if ($('.newsbox_toggle').hasClass('open')) { 
     //scroll to the top of the newsbox 
     $('html, body').animate({scrollTop: $('#header_lower').offset().top}, $speed); 
     $('#newsbox_content_wrapper').slideDown($speed, function() { 
      $('.newsbox_expand').html('Click to Close News Feature.').addClass('rotate'); 
     }); 
     $('.newsbox_toggle').removeClass('open'); 
    } else { 
     //scroll back to top of body 
     $('html, body').animate({ scrollTop: 0 }, $speed); 
     $('#newsbox_content_wrapper').slideUp($speed, function() { 
      $('.newsbox_expand').html('Click to Read More.').removeClass('rotate'); 
     }); 
     $('.newsbox_toggle').addClass('open'); 
    } 
}); 

, .bind()위한 속기 .click()를 사용합니다.

$('.newsbox_toggle').click(function() { 
    // ... 
}); 
+0

답변 해 주셔서 감사합니다. 내가 말했듯이, 나는 이것에 새로운 것이고, 체인은 내가 성취하고자하는 것에 가장 적합하다고 생각한다. 이걸 제대로 이해하면'.slideUp'이 완료된 후에'.html'이 실행됩니다. – mnelson7982

+0

네, 맞습니다. '.slideUp'에 전달한 (익명) 함수는 애니메이션이 완료된 후에 실행됩니다. 거의 모든 jQuery 애니메이션 메소드는 콜백을 지원합니다. –

+0

정말 고마워요. 당신은 매우 도움이되었습니다! – mnelson7982

1

당신이 (스크롤) 이동 : http://jsfiddle.net/zWnLv/43/

//hide wrapper at document ready and put in var for re-use 
var newsbox = $('#newsbox_content_wrapper').hide(); 

//toggle visiblility of newsbox and slide down to scroll window to newsbox 
$('.newsbox_toggle').bind('click', function() { 
    newsbox.slideToggle("slow",function() { 
     $('html, body').animate({ scrollTop: newsbox.offset().top }, 'slow'); 
    }); 

}); 

마찬가지로 지금까지 당신이 많은 옵션을 가지고 당신은 ... "를 더 읽기를 클릭"으로 매번 텍스트를 토글하거나 내 취향에 따라 +/- (또는 화살표) 배경 이미지로 클래스를 전환하여 사용자가 해당 섹션을 열거 나 닫을 수 있음을 직관적으로 알 수 있습니다.

+0

감사합니다. 문제는 토글 된 div가 상단에서 ~ 450 픽셀이며 펼쳐지면 폴드 아래로 확장됩니다. 그게 왜 div 아래로 스크롤하는 추가 코드를 추가했습니다. – mnelson7982

+0

@ mnelson7982 - 스크롤을 추가했습니다 (위의 코드를 참조하거나 http://jsfiddle.net/zWnLv/43/로 이동하십시오) - 건배 – themerlinproject

+0

텍스트를 유지하고 배경을 사용하고 싶습니다. Rotate 클래스는 CSS3 변환을 사용하여 jsFiddle 코드에서 생략 된 배경 이미지를 회전합니다. – mnelson7982