我正在尝试制作一个导航栏,该导航栏将固定在带有无序列表的页面一侧。列表项将通过 anchor 链接到页面。
但是,我希望 h2 元素根据单击固定导航栏中的哪个元素来更改颜色。
例如:当在导航中单击“home”时,它会将页面锚定到 id #home,然后还将 h2 颜色更改为事件颜色。然后,当在导航中单击“关于我们”时,需要从#home 中删除事件颜色,并将其添加到#about 中。
这需要通过 jquery 添加和删除类(也许?),但我还不够了解。我做了一个fiddle来表达我的观点。
这是我当前的 jquery 脚本,它将无法向事件 anchor 添加颜色:
$('#header li a').on('click', function() {
$('li a.current').removeClass('current');
$('#1').addClass('current');});
最佳答案
#1
位于您的 href 中,而不是链接的 ID。使用 this
可以获得点击的内容。
现在,如果您想更改 header ,则需要使用哈希值选择它
$('#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>
关于javascript - 通过单击 anchor href 更改标题颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40620663/