javascript - 滚动偏移脚本中的 preventDefault undefined

标签 javascript jquery scroll offset preventdefault

我正在使用这个脚本滚动到一个 anchor :

$( 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() 调用。


在您添加的评论中:

The problem is, because the scroll-to-element has an offset of -100, the page jumps a bit after it updates the URL. I want to prevent that, so that's why I have this e.preventDefault(); within the animate callback. If I remove it, it still makes this weird jump.

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

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

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

关于javascript - 滚动偏移脚本中的 preventDefault undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54039405/

相关文章:

Jquery Chrome 动画问题

javascript - 我如何在 jQuery 中操作这个对象

python - pygame - 向下滚动页面

jquery - float 菜单栏向上滚动时粘在顶部,一个替换另一个jquery

javascript - 如果 angularjs 模板中的其他条件

javascript - Backbone + Promises - 如何在发布后获取

javascript - 如何从jQuery对话框UI中隐藏按钮?

javascript - VueJS : Dynamic v-model inside v-for

jquery - .find() 多个类在一个语句中带有变量

javascript - 在vue js上滚动页面到div onload