Active Element JS for href="/"

Active Element JS for href="/"

本文关键字:quot href Element JS for Active      更新时间:2023-09-26

我想在当前页面的导航元素中添加一个"活动"类。除了索引页面外,它工作得很好,因为SEO和美观,我想保留索引网站的a href="/"链接。

有什么帮助吗?

$(function() {
  var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
  $(".menu-side a").each(function() {
    if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
      $(this).addClass("active");
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav class="menu-side">
  <a title="Startseite" href="/">Startseite</a>
  <a title="Über Mich" href="ueber_mich.html">Über Mich</a>
  <a title="Projekte" href="projekte.html">Projekte</a>
  <a title="Galerie" href="galerie.html">Galerie</a>
  <a title="Kontakt" href="kontakt.html">Kontakt</a>
  <a title="Impressum" href="impressum.html">Impressum</a>
</nav>

您可以随时检查是否设置了活动类,如果没有,则设置默认类:

$(function() {
  var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
  $(".menu-side a").each(function() {
    if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
      $(this).addClass("active");
  })
  if($(".menu-side a.active").length == 0) 
        $(".menu-side a:first").addClass('active');
});
a.active {color: green}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav class="menu-side">
  <a title="Startseite" href="/">Startseite</a>
  <a title="Über Mich" href="ueber_mich.html">Über Mich</a>
  <a title="Projekte" href="projekte.html">Projekte</a>
  <a title="Galerie" href="galerie.html">Galerie</a>
  <a title="Kontakt" href="kontakt.html">Kontakt</a>
  <a title="Impressum" href="impressum.html">Impressum</a>
</nav>

您可以使用sessionStorage保存单击的元素的href,当页面重定向时,您可以将重新应用到具有保存的href的元素,如下所示:

$("nav a").click(function() {
  $(this) siblings().removeClass("active").addClass("active");
  sessionStorage.nowActive = $(this).attr('href');
});
$(document).ready(function() {
  if (sessionStorage.nowActive != "undefined") {
    $("nav a").each(function() {
      if ($(this).attr("href") == sessionStorage.nowActive) {
        $(this).addClass("active");
      }
    });
  }
});

这是代码

JSFiddle