jQuery滚动到表单输入位置

3

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

我的当前代码可以工作,但屏幕会快速闪烁。我尝试使用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();
    });
});

你能否使用.scrollTo()代替.animate()呢?http://flesler.com/jquery/scrollTo/ - ntgCleaner
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();
        });
    });
});

谢谢Adeneo!通过将焦点放在动画回调中,它可以很好地工作! - Jared Michael Czerew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接