如何突出显示滚动菜单上的活动菜单项并单击? [英] How to highlighting active menu item on scroll and click?
问题描述
我要向滚动菜单上的当前菜单项添加类active
,然后单击.这是一个包含不同部分的单个(长)页面.单击一个项目时,活动状态应切换到当前状态.
I want to add a class active
to the current menu item on scroll and click. It’s a single (long) page with different sections. When click on an item, the active state should switch to the current one.
我想出了以下代码,但现在不知道如何集成以上代码:
I came up with the following code, but doesn’t now how I can integrate the above:
// 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
类.您只需要点击处理程序中的这段代码
To add active
class on click
is simple using jQuery. You just need this code in the click handler
//remove active from all anchor and add it to the clicked anchor
$('#primary-navwrapper li a[href^="#"]').removeClass("active")
$(this).addClass('active');
对于滚动部分,您需要监视滚动条的位置并将其与每个页面偏移量进行比较
And for the scroll part you need to monitor the position of the scroll bar and compare it with every page offset like so
//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');
}
})
这是一个演示 http://jsfiddle.net/k5afwfva/
这篇关于如何突出显示滚动菜单上的活动菜单项并单击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!