繁体   English   中英

通过单击锚href更改标题颜色

[英]changing a header color by clicking on an anchor href

我正在尝试制作一个导航栏,该导航栏将固定在页面的侧面,并显示无序列表。 列表项将通过锚点链接到页面。

但是,我希望一个h2元素根据单击固定导航栏中的哪个元素来更改颜色。

例如:在导航栏中单击“主页”时,它将在页面上定位到ID #home,然后还将h2颜色更改为活动颜色。 然后,在导航栏中单击“关于我们”时,它需要从#home中删除活动颜色,并将其添加到#about中。

这需要通过jquery(也许是?)添加和删除类,但是我只是不够了解。 我做了一个小提琴以阐明我的观点。

这是我当前的jquery脚本,它将无法向活动锚添加颜色:

$('#header li a').on('click', function() {
 $('li a.current').removeClass('current');
 $('#1').addClass('current');});

#1在您的href中,而不是链接的ID。 使用this您可以获得单击的内容。

现在,如果您想更改标题,则需要使用哈希将其选中

 $('#header li a').on('click', function() { $('li a.current, h2.current').removeClass('current'); //remove the current class from the link and h2 $(this).addClass('current'); //add current to the link that was clicked $(this.hash).addClass('current'); //add class to h2 using the hash which gives you the #1, #2 in the href of the link }); 
 a.current { background-color: yellow; } h2.current { background-color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="header"> <ul> <li><a href="#1">home</a></li> <li><a href="#2">about us</a></li> <li><a href="#3">directors</a></li> <li><a href="#4">admissions</a></li> </ul> </div> <div> <h2 id="1">home</h2> <h2 id="2">about us</h2> <h2 id="3">directors</h2> <h2 id="4">admissions</h2> </div> 

为了更改具有与链接中给定的id相同的id的h2元素的颜色,可以使用:

$('#header li a').on('click', function() {
    $('li a.current').removeClass('current');
    $($(this).attr('href')).addClass('current');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM