Jor*_*rdy 3 javascript jquery scroll offset preventdefault
我正在使用此脚本滚动到一个锚点:
$( 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;
}
});
});
Run Code Online (Sandbox Code Playgroud)
但是,在单击链接(并且动画完成)后,出现以下错误两次: 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;
}
});
});
Run Code Online (Sandbox Code Playgroud)
该animate回调并不接收事件对象。
目前尚不清楚您要阻止什么,因为您已经阻止了所发生事件的默认值(点击)。只需删除e上面指示的内容以及回调e.preventDefault()中的animate调用。
在您添加的评论中:
问题是,因为滚动到元素的偏移量为 -100,所以页面在更新 URL 后会跳转一点。我想阻止这种情况,所以这就是为什么我有这个 e.preventDefault(); 在动画回调中。如果我删除它,它仍然会产生这种奇怪的跳跃。
它没有调用跳转的唯一原因是调用抛出错误,所以下一行永远不会运行,所以它永远不会设置 URL。
如果要在不更改页面或滚动位置的情况下设置 URL,请history.replaceState改用:
history.replaceState(null, "", href);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |