2012-08-31 73 views
2

我想將焦點設置爲id的文本框讓我們說,使用div.focus和animate()滾動到頁面頂部後,txtName。如何在設置動畫後設置焦點

是否有一個功能,指定在像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); 
}