在锚链接 jQuery 内滚动动画



当有人访问锚链接时,我正在尝试制作滚动动画,如下所示:

www.miweb.com/section/#anchorLink

我正在用这段代码来做,但它有问题,因为我无法在它之后执行任何其他内容(在这种情况下为 alert("结束"),以防用户在没有锚 ID 的情况下访问 URL。

$('html, body').animate({
    scrollTop:$('[name="'+window.location.hash.replace("#", "")+'"]').offset().top
}, 500);
alert("the end");

如果用户从具有定位点 ID 的 URL 访问,则将执行该 URL。

在任何情况下,我该如何在此函数之后执行代码?

谢谢。

如果要在

动画之后执行代码,请执行以下操作:

$('html, body').animate({
    scrollTop:$('[name="'+window.location.hash.replace("#", "")+'"]').offset().top
}, 500, function() {
    alert("the end");
});

更新
在 OP 的评论之后,我认为当 offset() 为 null 时(没有锚点时就是这种情况),您在访问 top 属性时遇到 javascript 错误,因此您可以防止访问可能的 null 引用,如下所示:

dest = $('[name="'+window.location.hash.replace("#", "")+'"]').offset();
dtop = dest != null ? dest.top : null;
$('html, body').animate({
    scrollTop: dtop
}, 500);
alert("the end");​

现在alert()打印应该可以正常了。

如果您查看浏览器 javascript 控制台,您将来可以轻松发现类似的错误,我只是这样做并看到了有关 null 引用的错误。

最新更新