根据URL添加活动导航类

45

我正在尝试在页面加载完成后,根据当前页面将active类(例如class="active")添加到相应的菜单项。以下是我的菜单代码。我尝试过各种相关的代码片段,但都无法实现。请问有谁能简单地解释在何处以及如何添加javascript来定义此任务?

<ul id="nav">
    <li id="navhome"><a href="home.aspx">Home</a></li>
    <li id="navmanage"><a href="manageIS.aspx">Manage</a></li>
    <li id="navdocso"><a href="docs.aspx">Documents</a></li>
    <li id="navadmin"><a href="admin.aspx">Admin Panel</a></li>
    <li id="navpast"><a href="past.aspx">View Past</a></li>
</ul>

这是我在网站主控制文件的头部标签中放置的JavaScript示例。我做错了什么吗?

$(document).ready(function () {
    $(function () {
        $('li a').click(function (e) {
            e.preventDefault();
            $('a').removeClass('active');
            $(this).addClass('active');
        });
    });
});

2
OP 无关 但对于使用 Bootstrap 4 的简单用例$(function () { $(\.nav-link[href="${location.pathname}"]`).parent().addClass("active"); });` - Givi
25个回答

1

我知道这个回答有点晚,但对我来说还不错

var links = document.querySelectorAll('li a');

for (link of links) {
    if (window.location.pathname == link.getAttribute('href')) {
        link.classList.add('active')
    } else {
        link.classList.remove('active')
    }
}

1

jQuery风格:

$('a[href="'+ window.location.href + '"]').css({
  backgroundColor: 'red',
  color: 'white'
})

如果你有相对链接,请在第一行使用以下内容:

$('a[href="'+ window.location.path + '"]').css({

或者两者都可以。
$('a[href="'+ window.location.href + '"], a[href="'+ window.location.path + '"]').css({

1
这应该可以在一行代码中完成你的工作。
document.querySelector(`a[href^='${location.pathname.split('/'[1])}']`).className = 'active'

1

我知道这个问题被问了很长时间。以下是一个不需要使用jQuery就能解决的答案:

var activeNavlink = document.querySelectorAll('nav a[href^="/' + location.pathname.split("/")[1] + '"]');
activeNavlink[0].classList.add('active');

希望这有所帮助。

1

这对我来说完美地运作了。

$(function($) {
 let url = window.location.href;
  $('nav ul li a').each(function() {
   if (this.href === url) {
   $(this).addClass('active');
  }
 });
});

1
如果您想在 asp.net 中使用主页面,只需将此代码放在 body 标签内。
 <script type="text/javascript">
    jQuery(function ($) {
        var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
        $('ul a').each(function () {
            if (this.href === path) {
                $(this).addClass('active');
            }
        });
    });
</script>

谢谢你。

0
以下是将动态的活动类添加到导航栏元素的解决方案。
// first lets get all the navbar elements.
const navElements = document.querySelectorAll(".list");
// creating a function of active navbar item 
const activeLink = (el) => {
        list.forEach((item) => {
         item.classList.remove("active");
         el.classList.add("active");
    });
 };


// attaching the event listener for each element
list.forEach((item) => {
    item.addEventListener("click", () => {
       activeLink(item)
    });
 });

今天我遇到了一个问题,即如何动态添加活动类到链接?当我找到解决方案时,我想帮助其他人。 - Kashif Ali

0

这对我来说完成了工作... 将其放置在body标记的结束之前

 $(function () {
        var current = location.pathname;
        console.log(current);
        if (current == "/") {
            $('#home').addClass('active'); //#home is the id for root link.
        }
        else {

            $('#navbarCollapse div a').each(function () {
                var $this = $(this);
                // if the current path is like this link, make it active
                if ($this.attr('href').indexOf(current) !== -1) {
                    $this.addClass('active');
                }
            })
        }
    })

0

我在使用Networker的示例时遇到了一个问题,即如果选择任何页面,则根链接会亮起。这将防止根页面出现此问题:

function setActive() {
  linkObj = document.getElementById('menu').getElementsByTagName('a');
  for(i=0;i<linkObj.length;i++) { 
    const url = new URL(window.location.href);
    if((document.location.href.indexOf(linkObj[i].href)>=0 && linkObj[i].href != url.protocol+"//"+url.hostname+"/") || document.location.href == linkObj[i].href) {
      linkObj[i].classList.add("active");
    }
  }
}
window.onload = setActive;

0

类可以让编程生活变得更加轻松。

CSS

<nav>
    <ul class="nav-list">
        <li class="nav-list-item"><a class="nav-link nav-link-active" href="index.html">Home</a></li>
        <li class="nav-list-item"><a  class="nav-link" href="about.html">About Me</a></li>
        <li class="nav-list-item"><a  class="nav-link" href="posts.html">Recent Posts</a></li>
    </ul>
</nav>

js

(function() {
    current_page = window.location.href;
    navlinks = document.getElementsByClassName("nav-link");
    active_page = document.getElementsByClassName("nav-link-active")[0];
    if (active_page) {
        active_page.classList.remove("nav-link-active");
    }

    for (i=0; i < navlinks.length; i++) {
        if (navlinks[i].href == current_page) {
            navlinks[i].classList.add("nav-link-active");
            break;
        }
    }
})();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接