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

Javascript 当站在当前扇区(id)上时,菜单链接在一页webiste上突出显示。,javascript,jquery,Javascript,Jquery,因此,当滚动到单页网站的相应扇区(id)时,我选择突出显示活动菜单链接。然而,它并不完美,因为当我点击导航栏中的一个opf菜单链接时,有时它只是跳转到另一个opf菜单链接 谁能帮我解决这个问题 JS: $(文档).ready(函数(){ $(文档).on(“滚动”,onScroll); //平滑卷轴 $('a[href^=“#“]”)。关于('click',函数(e){ e、 预防默认值(); $(文档)。关闭(“滚动”); $('a')。每个(函数(){ $(this.removeClass(

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

谁能帮我解决这个问题

JS:

$(文档).ready(函数(){
$(文档).on(“滚动”,onScroll);
//平滑卷轴
$('a[href^=“#“]”)。关于('click',函数(e){
e、 预防默认值();
$(文档)。关闭(“滚动”);
$('a')。每个(函数(){
$(this.removeClass('active');
})
$(this.addClass('active');
var target=this.hash,
菜单=目标;
$target=$(target);
$('html,body').stop().animate({
'scrollTop':$target.offset().top+2
},500,'swing',函数(){
window.location.hash=目标;
$(文档).on(“滚动”,onScroll);
});
});
});
函数onScroll(事件){
var scrollPos=$(document.scrollTop();
$('#myNavbar a')。每个(函数(){
var currLink=$(此);
var refElement=$(currLink.attr(“href”);
if(refElement.position().top scrollPos){
$('myNavbar ul li a').removeClass(“活动”);
currLink.addClass(“活动”);
}否则{
currLink.removeClass(“活动”);
}
});
}
对不起,这是一个难看的代码,因为我只是复制粘贴在这里,没有修复它

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

谢谢大家!

变化:

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

if(refElement.position().top+20滚动位置)
你可以玩这20个,然后把它改成最适合你的

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