2014-01-22 51 views
1

我试图在网页上scrollTo(),我想要一个按钮来触发scrollTo();它将滚动到窗体的顶部并突出显示第一个输入字段。jquery滚动到表单输入

我的当前代码有效,但屏幕快速闪烁。我试图使用preventDefault()无济于事。请参阅下面的代码。

$(document).ready(function() { 
    $("#get-started").click(function (e) { 
     e.preventDefault(); 
     $('html, body').animate({ 
      scrollTop: $("#get-risk").offset().top 
     }, 2000); 
     $("#get-started-apply-now-form [name='last_name']").focus(); 
    }); 
}); 
+0

而不是使用'.animate()',你可以使用'.scrollTo()'吗? http://flesler.com/jquery/scrollTo/ – ntgCleaner

回答

6

当对某个元素进行聚焦时,浏览器会滚动到该元素,从而搞乱了动画。

将焦点放在动画回调中以避免它。

$(document).ready(function() { 
    $("#get-started").click(function (e) { 
     e.preventDefault(); 
     $('html, body').animate({ 
      scrollTop: $("#get-risk").offset().top 
     }, 2000, function() { 
      $("#get-started-apply-now-form [name='last_name']").focus(); 
     }); 
    }); 
}); 
+0

谢谢adeneo!通过将重点放在动画回调中,它的效果非常好! –