我正在尝试更改列表的类<李>当我滚动到它时,element to class =“active”。
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#menu').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#menu ul li').removeClass("active"); //added to remove active class from all a elements
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
这是我的菜单
<div class="navbar navbar-inverse" data-spy="affix" id="header" role="navigation" data-offset-top="100">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div class="navbar-collapse collapse" id="menu">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#">Testimonials</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="dropdown-header">Description Header</li>
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">More links</a></li>
<li><a href="#">And one to grow on</a></li>
</ul>
</li>
<li><a href="#">Contact</a></li>
</ul>
</div><!--/.navbar-collapse -->
</div>
</div>
我不确定我是否正确修改了列表元素。平滑滚动工作正常,但课程不会改变。
谢谢!
答案 0 :(得分:0)
尝试,
$("li").click(function(){
$(".active").removeClass(".actvie");
$(this).addClass("active");
});