2012-08-31 4 views
2

div.focus 및 animate()를 사용하여 페이지 상단으로 스크롤 한 후 txtName을 말하도록 id의 텍스트 상자에 포커스를 설정하려고합니다.애니메이션 후 초점 설정 방법

document.ready가 document.ready 다음에 수행하는 것처럼 애니메이션 후에 초점을 지정하는 기능이 있습니까?

스크롤 할 때 사용한 코드는 다음과 같습니다.

$(".gototop").click(function(){ 
    var focusElement = $("#contents"); 
    $(focusElement).focus(); 
    ScrollToTop(focusElement); 
}); 

function ScrollToTop(el) { 
    $('html, body').animate({ scrollTop: $(el).offset().top - 50 }, 'slow');   
} 

답변

9

당신은 애니메이션의 콜백 요소에 애니메이션이 완료 될 때 포커스를받는 그런 식으로 초점을 설정할 수 있습니다

function ScrollToTop(el) { 
    $('html, body').animate({ 
     scrollTop: $(el).offset().top - 50 }, 
    'slow', function() { 
     $("#txtName").focus(); 
    });   
} 

el 당신이 포커스를 맞추려는 요소가있는 경우, 당신이 할 수있는 #txtName 대신에 전달 된 변수 사용

+0

당신은 저를 이겼습니다. @Archie Dave, 애니메이션에 대한 jQuery 문서를 참조하십시오. 여기서 "complete"매개 변수는 애니메이션이 완료 될 때 호출 할 함수입니다. http://api.jquery.com/animate/ – devlord

2

animate 함수는 애니메이션이 완료되면 실행될 콜백을 허용합니다. 당신은 다음과 같이 할 수 있습니다 :

$(".gototop").click(function(){ 
    var focusElement = $("#contents"); 
    ScrollToTop(focusElement, function() { focusElement.focus(); }); 
}); 

function ScrollToTop(el, callback) { 
    $('html, body').animate({ scrollTop: $(el).offset().top - 50 }, 'slow', callback); 
}