我正在网页上尝试使用 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();
});
});
最佳答案
当聚焦某个元素时,浏览器会滚动到该元素,从而扰乱您的动画。
将焦点放在动画回调中以避免它。
$(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();
});
});
});
关于jquery滚动到表单输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21292128/