【发布时间】:2020-03-31 22:27:06
【问题描述】:
我不是 JS 开发人员,我正在使用 Bootstrap 构建一个带有锚链接的单页站点。
我正在使用我找到的任何点点滴滴的 JS 代码来实现一些必要的功能,例如为锚链接添加平滑滚动,顶部偏移,因为我使用的是固定/粘性菜单。
虽然它是一个单页网站,但我将隐私和条款作为单独的页面使用。
这是我用于主页上的锚链接的代码。我认为这是 JS 和 jQuery 的混合体。它运作良好,符合我的要求。
$('.navbar a, .smooth-scroll-contact').on('click', function(event) {
/* Make sure this.hash has a value before overriding default behavior */
if (this.hash !== "") {
/* Prevent default anchor click behavior */
event.preventDefault();
/* Store hash */
var hash = this.hash;
/* Using jQuery's animate() method to add smooth page scroll. */
$('html, body').animate({
scrollTop: $(hash).offset().top - 70
}, 800, function(){
/* Add hash (#) to URL when done scrolling (default click behavior). */
if (history.pushState) {
history.pushState(null, null, hash);
}
else {
window.location.hash = hash;
}
});
} // End if
});
虽然它在主页上运行良好,但它会阻止菜单链接在隐私和条款页面上打开。单击那里的菜单链接时,它什么也不做。它不会转到主页或那里的任何锚链接。
这是在“隐私”或“条款”页面上单击菜单链接时出现在控制台中的错误:
Uncaught TypeError: Cannot read property 'top' of undefined
at HTMLAnchorElement.<anonymous> (custom.js:39)
at HTMLAnchorElement.dispatch (jquery-3.4.1.min.js:2)
at HTMLAnchorElement.v.handle (jquery-3.4.1.min.js:2)
第 39 行是scrollTop: $(hash).offset().top - 70。
我搜索了这个错误并尝试应用我找到的一些修复,但它们对我不起作用,或者我不知道如何为这个特定代码正确实现它们。
补充说明:
- 如果我去掉平滑滚动代码,问题就解决了;
- 找到代码的
custom.js文件在</body>之前加载; - jQuery 是第一个加载的脚本。
如果您需要更多信息,请告诉我。
【问题讨论】:
标签: javascript jquery