切换页面当前部分的菜单颜色
我正在制作一个单页网站,其中菜单是固定的,因此当用户单击链接时,它会向下滚动到页面的该部分。用户所在部分的菜单链接应具有不同的颜色。为此,我有“当前”课程。我正在尝试使用 jQuery addClass() 和 removeClass() 进行此更改,但没有运气。到目前为止我的代码如下。
$(document).ready ( function(){
$(".about").click(function(){
$(".home").removeClass("current");
$(".about").addClass("current");
});
});
编辑:
菜单 HTML:
<nav id="nav_list">
<ul>
<li class="home current"><a href="#">Home</a></li>
<li class="about"><a href="#about">About</a></li>
<li class="portfolio"><a href="#portfolio">Portfolio</a></li>
<li class="testimonials"><a href="#testimonials">Testimonials</a></li>
<li class="contact"><a href="#contact">Contact</a></li>
</ul>
</nav>
div HTML:(
<div id="about" class="page">
<p>Lorem ipsum dolor sit</p>
</div>
每个菜单链接都有一个 div。)
编辑2
css:
#nav_list .current a{
color: #D4D1FA;
}
我注意到,如果删除#nav_list,我不会从一开始就看不到颜色的变化。
I'm making a one-page site where the menu is fixed, so when the user clicks a link it scrolls down to that part of the page. The menu link of the section the user is on should have a different color. For this I have the class "current." I'm trying to make this change with jQuery addClass() and removeClass(), but am having no luck. The code I have so far is below.
$(document).ready ( function(){
$(".about").click(function(){
$(".home").removeClass("current");
$(".about").addClass("current");
});
});
EDIT:
menu HTML:
<nav id="nav_list">
<ul>
<li class="home current"><a href="#">Home</a></li>
<li class="about"><a href="#about">About</a></li>
<li class="portfolio"><a href="#portfolio">Portfolio</a></li>
<li class="testimonials"><a href="#testimonials">Testimonials</a></li>
<li class="contact"><a href="#contact">Contact</a></li>
</ul>
</nav>
div HTML:
<div id="about" class="page">
<p>Lorem ipsum dolor sit</p>
</div>
(There is a div to go with each menu link.)
EDIT2
css:
#nav_list .current a{
color: #D4D1FA;
}
I noticed that if I remove the #nav_list, I don't see a change in color from the start.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个 - 它会从所有列表项中删除当前类,并将该类添加到单击的列表项中。
不过要回答您的具体用例。将链接设置为显示为块。这会导致他们填满列表项容器。然后监视链接单击而不是列表项单击。之前发生的情况是,单击链接不会触发对列表项容器的单击,因此您的添加/删除类代码可能永远不会触发。通过使其填充您捕获所有点击的区域。
http://jsfiddle.net/hkZsL/
css
javascript
Try this - it removes the current class from all list items and adds the class to the clicked one.
To answer your specific use case though. Set your links to display as block. This causes them to fill their list item containers. Then monitor the link click instead of the list item click. What was happening before was that clicking on the link did not trigger a click on the list item container, so your add/remove class code probably was never firing. By making it fill the area you capture all clicks.
http://jsfiddle.net/hkZsL/
css
javascript