javascript - 通过单击 anchor href 更改标题颜色

标签 javascript jquery colors html-lists

我正在尝试制作一个导航栏,该导航栏将固定在带有无序列表的页面一侧。列表项将通过 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/

相关文章:

javascript - 使用 JavaScript 或 jQuery,如何检查选择框是否与原始值匹配?

javascript - 如何将制表符分隔格式的文本文件的内容显示为 html 表格

javascript - get() 无法找到 POST 数据

r - 在颜色空间中的scale_fill/color中粘贴名称不能循环工作

javascript - 如何从具有多个组件的文件中导入组件

javascript - 搜索表单没有重置,这里出了什么问题?

javascript - 通过启用新元素的拖放来解决 jquery 性能问题

php - 搜索正文内容,用弹出窗口突出显示

python - 如何将十六进制三元组转换为 RGB 元组并返回?

r - 如何使用 scale_color_brewer 修复 'continuous value supplied to discrete scale'