简体   繁体   English

带锚点的主动式 class 导航侧边栏

[英]Active class navigation sidebar with anchors

I have a navigation sidebar with several anchors in an xsl document.我在 xsl 文档中有一个带有多个锚点的导航侧边栏。 Based on Adding active class for two anchor tags suggestions, I have tried to apply the same script, but I don't see why there is no modification of the style according to CSS.基于为两个锚标签建议添加活动 class ,我尝试应用相同的脚本,但我不明白为什么没有根据 CSS 修改样式。

<script>
     <![CDATA[
       document.querySelectorAll("#menu-hermeneutics li > a").forEach(a => {
          a.addEventListener("click", () => {
              a.addClass('active'); 
          });
       });]]>
</script>
<ul id="menu-hermeneutics">
    <li><a href="#general-overview">General Overview</a></li>
    <li><a href="#context-overview">...</a></li>
    <li><a href="#result-overview">...</a></li>
    <li><a href="#clanA">...</a></li>
    <li><a href="#aff-clanA">...</a></li>
    <li><a href="#clanB">...</a></li>
    <li><a href="#aff-clanB">...</a></li>
    <li><a href="#DR">...</a></li>
    <li><a href="#clanUNK">...</a></li>                
</ul>

And CSS:和 CSS:

#menu-hermeneutics > .active {background-color: grey; color: white; font-weight: 700; margin-right: 100px; width: 200px; }

In advance, thanks for your kind help.在此先感谢您的帮助。

First of all, your code at document.querySelectorAll("#menu-hermeneutics li > a") means it's gonna query all a tag and add class active if clicked on it, but your css below, it's different.首先,您在document.querySelectorAll("#menu-hermeneutics li > a")a代码意味着它将查询所有标签并在单击它时添加 class active ,但您的 css 下面是不同的。 #menu-hermeneutics >.active means it will select #menu-hermeneutics 's children (here is li , not a ) with class active because you are using > . #menu-hermeneutics >.active意味着它将 select #menu-hermeneutics的孩子(这里是li ,不是a )与 class active ,因为你正在使用> If you want to css at all children a only, you can do this #menu-hermeneutics a.active You can take a look at here for more details.如果你想 css 在所有的孩子a ,你可以这样做#menu-hermeneutics a.active你可以看看这里了解更多细节。 Hope it would help希望它会有所帮助

Thanks to the suggestions of @ThienHuynh and a colleague, this is the correct code:感谢@ThienHuynh 和一位同事的建议,这是正确的代码:

var links = document.querySelectorAll("#menu-hermeneutics li a");
  for (const link of links) {
    link.addEventListener("click", (e) => {
    var target = e.target;

    links.forEach(function(currentLink) {
        currentLink.classList.remove('active');
    });

      // if target already had .active. remove it. Otherwise, add it
      target.classList.toggle('active');
    })
    }

Note: see my comment below regarding > vs &gt --it was the main problem to avoid a bug.注意:请参阅下面关于> vs &gt的评论——这是避免错误的主要问题。

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

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