我正在使用这个脚本滚动到一个 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/