可能这个问题以前已经回答过很多次,但我找不到与我的代码相关的任何内容。
一切正常,当菜单导航打开时,等等 smooth scrolling
也可以正常工作,除非我单击 arrow-down
进入下一节,平滑滚动不起作用。我一直在看它并试图弄清楚一段时间,但我无法这样做。
我还在学习 jquery 和 javascript。可以在 此处找到此代码的完整演示。 打开开发工具,您将在控制台中看到错误。
编辑 添加..
.arrow-down-wrapper a[href^="#"]
至
$('nav.mobile-nav a[href^="#"], .arrow-down-wrapper a[href^="#"]').on('click', function (e) {
...
}
平滑滚动不适用于“向下箭头”,但我仍然收到“Uncaught TypeError: Cannot read property ‘top’ of undefined”
console.log(target);
输出正确的目标。 #Home、#about 等等。
这是我的代码:
//smooth transition to sctions when links in header are clicked
function onScroll(event){
var scrollPosition = $(document).scrollTop();
$('nav.mobile-nav a').each(function () {
var currentLink = $(this);
var refElement = $(currentLink.attr("href"));
if (refElement.position().top <= scrollPosition && refElement.position().top + refElement.height() > scrollPosition) {
$('nav.mobile-nav a').removeClass("current");
currentLink.addClass("current");
}
else{
currentLink.removeClass("current");
}
});
}
$(document).ready(function () {
$(document).on("scroll", onScroll);
$('nav.mobile-nav a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('nav.mobile-nav a').each(function () {
$(this).removeClass('current');
});
$(this).addClass('current');
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 1000, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
原文由 Guille 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是代码不够具体。循环遍历列表中的所有项目,即#tags 所在的所有链接,以及指向其他页面的链接。这就是我收到 top not defined 错误的原因,它正在寻找的那个项目不存在。
a[href^="#"'
添加后,循环仅迭代带有# ID 标签的项目。评论了我所做的更改
//单击标题中的链接时平滑过渡到部分