防止滚动偏移脚本中未定义默认值



我正在使用此脚本滚动到锚点:

$( document ).ready(function(e) 
{
    var $root = $('html, body');
    $('a').click(function(e) {
        e.preventDefault();
        var href = $.attr(this, 'href');
        if(href!=='javascript:void(0)' && href!=='javascript:void(0);'){
            $root.animate({
                scrollTop: $(href).offset().top-100
            }, 1000, function (e) {
                e.preventDefault();
                window.location.hash = href;
            });
            return false;
        }
    });
});

但是,在我单击链接(并且动画完成)后,我收到以下错误两次:Uncaught TypeError: Cannot read property 'preventDefault' of undefined

我不明白为什么。我试图将e添加到函数中,但它仍然给出错误。有人可以提供一些背景信息吗?

问题是...

$( document ).ready(function(e) 
{
    var $root = $('html, body');
    $('a').click(function(e) {
        e.preventDefault();
        var href = $.attr(this, 'href');
        if(href!=='javascript:void(0)' && href!=='javascript:void(0);'){
            $root.animate({
                scrollTop: $(href).offset().top-100
            }, 1000, function (e) {
//                             ^−−−−−−−−−−−−−−−−−−−−−− here
                e.preventDefault();             // <−− and/or (arguably) here
                window.location.hash = href;
            });
            return false;
        }
    });
});

animate回调不会收到事件对象。

目前尚不清楚您当时要阻止什么,因为您已经阻止了所发生事件的默认值(点击)。只需删除上述e以及animate回调中的e.preventDefault()调用即可。


在您添加的评论中:

问题是,由于滚动到元素的偏移量为 -100,因此页面在更新 URL 后会跳转一点。我想防止这种情况,所以这就是为什么我有这个 e.preventDefault();在动画回调中。如果我删除它,它仍然会做出这种奇怪的跳跃。

没有与调用跳转的唯一原因是调用抛出错误,因此下一行永远不会运行,因此它永远不会设置 URL。

如果要在不更改页面或滚动位置的情况下设置 URL,请改用history.replaceState

history.replaceState(null, "", href);

最新更新