当站在当前扇区(id)上时,菜单链接会在一页的webiste上突出显示



因此,当滚动到一页网站的适当扇区(id(时,我选择了突出显示活动菜单链接。然而,它并不完美,因为当我点击导航栏中的菜单链接时,有时它只是跳到另一个。

有人能帮我解决这个问题吗?

JS:

$(document).ready(function () {
$(document).on("scroll", onScroll);
//Smoothscroll
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#myNavbar a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + 
refElement.height() > scrollPos) {
$('#myNavbar ul li a').removeClass("active");
currLink.addClass("active");
}else{
currLink.removeClass("active");
}
});
}

很抱歉有一个丑陋的代码,因为我只是复制粘贴到这里,没有修复它。

要了解我在说什么/在想什么,你可以查看我的网站vlad095.github.io

谢谢!

更改:

if (refElement.position().top <= scrollPos && refElement.position().top + 
refElement.height() > scrollPos)

if (refElement.position().top + 20 <= scrollPos && refElement.position().top + 
refElement.height() - 20 > scrollPos)

你可以用20来打球,然后把它变成对你最好的。

最新更新