我想从当前页面向导航元素添加“活动”类。它的工作正常,除了索引页面,我想保留索引网站的href =“/”链接,因为SEO和美学。
有任何帮助吗?
$(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>
答案 0 :(得分:1)
您始终可以检查是否设置了活动类,如果没有,则设置默认值:
$(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>
答案 1 :(得分:0)