在窗口滚动上更改导航活动类 [英] Change navigation active class on window scroll
本文介绍了在窗口滚动上更改导航活动类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要创建一个滚动效果,如下所示 http://www.strikingly。 com / s / pages / default-ion?demo = ion#1
我现在需要的是改变导航li类当窗口滚动时激活,只需改变它使用< a href ='#about'>
哈希目标
i want to create a scroll effect like here http://www.strikingly.com/s/pages/default-ion?demo=ion#1
All i need for this moment is to change navigation li class active when the window is scrolling , just change the it using <a href='#about'>
hash target
http://jsfiddle.net/Dxtyu/131/
推荐答案
Serlite 的代码非常好,但有一些错误。
Serlite's code is very good but had some bugs.
- 如果向下滚动到最后两个
a
元素有活动
/ li>
- If you scroll down to the end last two
a
elements haveactive
class so both are highlighted.
解决方案
已添加<$ c $在下面的代码中添加新类之前,删除所有以前的活动类。
added $('#menu-center ul li a').removeClass("active");
to remove all previous active class before adding new class in the below code.
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#menu-center a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#menu-center ul li a').removeClass("active"); //added to remove active class from all a elements
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}
- 如果您点击第二个或更多的菜单链接
解决方案
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
这篇关于在窗口滚动上更改导航活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文