[英]Confused about highlighting active menu item on scroll (Vanilla JS)
[英]How to highlighting active menu item on scroll and click?
我想向滾動菜單上的當前菜單項添加active
的類,然后單擊。 這是一個包含不同部分的單個(長)頁面。 單擊一個項目時,活動狀態應切換到當前狀態。
我想出了以下代碼,但現在不知道如何集成以上代碼:
// Click event
$('#primary-navwrapper li a[href^="#"]').click(function(event) {
// Prevent from default action to intitiate
event.preventDefault();
// The id of the section we want to go to
var anchorId = $(this).attr('href');
// Our scroll target : the top position of the section that has the id referenced by our href
var target = $(anchorId).offset().top - offset;
console.log(target);
$('html, body').stop().animate({ scrollTop: target }, 500, function () {
window.location.hash = anchorId;
});
return false;
});
使用jQuery在click
添加active
類很簡單。 您只需在點擊處理程序中使用此代碼
//remove active from all anchor and add it to the clicked anchor
$('#primary-navwrapper li a[href^="#"]').removeClass("active")
$(this).addClass('active');
對於滾動部分,您需要監視滾動條的位置並將其與每個頁面偏移量進行比較,如下所示
//check the pages when scroll event occurs
$(window).scroll(function(){
// Get the current vertical position of the scroll bar
position = $(this).scrollTop();
$('#primary-navwrapper li a[href^="#"]').each(function(){
var anchorId = $(this).attr('href');
var target = $(anchorId).offset().top - offset;
// check if the document has crossed the page
console.log(position,target);
if(position>=target){
//remove active from all anchor and add it to the clicked anchor
$('#primary-navwrapper li a[href^="#"]').removeClass("active")
$(this).addClass('active');
}
})
<nav>
<a href="#" class="item">item</a>
<a href="#" class="item">item</a>
<a href="#" class="item">item</a>
<a href="#" class="item">item</a>
</nav>
var el = $(".item"),
yPos = 0;
el.click(function(event){
event.preventDefault();
$(this).addClass("active").siblings().removeClass("active");
});
$(window).scroll(function(){
yPos = $(this).scrollTop();
//i'm almost sure that you will need to calculate offset of your section to know when to switch classes
if(yPos > 100){
el.removeClass("active").eq(1).addClass("active");
}
if(yPos > 200){
el.removeClass("active").eq(2).addClass("active");
}
//etc....
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.