3

我正在尝试scrollTo()在网页上使用一个按钮来触发scrollTo();它将滚动到表单顶部并突出显示第一个输入字段。

我当前的代码有效,但是屏幕快速闪烁。我尝试使用 apreventDefault()无济于事。请在下面查看我的代码。

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

1 回答 1

12

当聚焦一个元素时,浏览器会滚动到那个元素,弄乱你的动画。

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

$(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();
        });
    });
});
于 2014-01-22T19:32:03.580 回答