根据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个回答

79
这不起作用的原因是由于JavaScript先执行,然后页面重新加载,这使得“active”类被取消。你可能想要做的是:
$(function(){
    var current = location.pathname;
    $('#nav li 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');
        }
    })
})

有些情况下这种方法可能行不通(多个相似的链接),但我认为这对你可能有用。


1
谢谢。使用这种方法并在我的链接前面添加“/”(例如 /home.aspx 而不是 home.aspx)纠正了问题。 - slybitz
@RobM 如果你的 ul 中有一个 ul,你该如何在顶层链接上设置活动类? - mjcoder
1
@MJCoder $this.parents('.target-parent-selector').addClass('active') - Rob M.
我们如何在Angular 8中实现这一点?我尝试使用routerLinkActive,但它不起作用。有人能提供一些见解吗? - Shobhit
@CodaBae 你可以使用 $this.closest('li').addClass('active') 或者如果 ali 的子元素,则使用 $this.parent().addClass('active') - Harry B
显示剩余3条评论

25

    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');
      }
     });
    });
.active, a.active {
    color: red;
}
a {
    color: #337ab7;
    text-decoration: none;
}
li{
    list-style:none;
}
<h3>Add Active Navigation Class to Menu Item</h3> 

    <ul>
     <li><a href="/">Home</a></li>
     <li><a href="/about/">About</a></li>
    </ul> 

<h2><a href="http://www.sweet-web-design.com/examples/active-item/active-class.html">Live Demo</a></h2>


18

使用纯VANILLA JavaScript

(function () {
    var current = location.pathname.split('/')[1];
    if (current === "") return;
    var menuItems = document.querySelectorAll('.menu-item a');
    for (var i = 0, len = menuItems.length; i < len; i++) {
        if (menuItems[i].getAttribute("href").indexOf(current) !== -1) {
            menuItems[i].className += "is-active";
        }
    }
})();

3
除了用 "is-active" 替换 'a' 元素中所有现有类之外,它的功能完美。为了解决这个问题,我将您代码片段中的第7行更改为 menuItems[i].className += " is-active"; ,似乎已经解决了问题。 - SeRosiS

6

ES6版本可以在以下情况下正常工作:当您的链接指向“/products”时,且您有子路由,例如:“/products/new”,“/products/edit”等。

let switchNavMenuItem = (menuItems) => {

    var current = location.pathname

    $.each(menuItems, (index, item) => {

        $(item).removeClass('active')

        if ((current.includes($(item).attr('href')) && $(item).attr('href') !== "/") || ($(item).attr('href') === "/" && current === "/")){
            $(item).addClass('active')
        }
    })
}

$(document).ready(() => {   
    switchNavMenuItem($('#nav li a, #nav li link'))
})

3
如果你的菜单需要在 li 中添加 active 类,那么你需要使用以下代码。
$(function($) {
  let url = window.location.href;
  $('nav ul li a').each(function() {
    if (this.href === url) {
      $(this).closest('li').addClass('active');
    }
  });
});

3

以上的解决方案都没有对我起作用。最终,这个JavaScript解决方案起了作用。

原始答案:Original Answer

<script>
function setActive() {
  linkObj = document.getElementById('premier-topnav').getElementsByTagName('a');
  for(i=0;i<linkObj.length;i++) { 
    if(document.location.href.indexOf(linkObj[i].href)>=0) {
      linkObj[i].classList.add("active");
    }
  }
}

window.onload = setActive;
</script>    

premier-topnav是导航栏div的id。
.active类被定义为:

#premier-topnav .active {
    color: brown;   
}

最好使用document.location.pathname === linkObj[i].getAttribute('href'),否则你将很难处理主页。 - Adam
谢谢你的回答。我正在学习JS,花了几个小时才得到一些结果,但多亏了你的代码片段,我找到了正确的方向。@Adam,你能解释一下你的建议吗? - ironixx

2
$(function() {
    var CurrentUrl= document.URL;
    var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();

    $( ".top-menu li a" ).each(function() {
          var ThisUrl = $(this).attr('href');
            var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();
            if(ThisUrlEnd == CurrentUrlEnd)
            $(this).addClass('active')
        });
    });

2

这段页面JS代码是百分百可行的,只需要将您的id放入其中即可享受它。

Original Answer翻译成"最初的回答"

   <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
   <script>
   $(document).ready(function() {

            var CurrentUrl= document.URL;
            var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();
            console.log(CurrentUrlEnd);
            $( "#lu-ID li a" ).each(function() {
                  var ThisUrl = $(this).attr('href');
                  var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();

                  if(ThisUrlEnd == CurrentUrlEnd){
                  $(this).closest('li').addClass('active')
                  }
            });

   });


这对我来说非常有效,点赞。谢谢! - Jawad Anwar

1

Rob.M说得对。

我将发布我的解决方案,因为他的对我来说并没有真正起作用。与他相比,我有一个小变化,假设您有不同的路径到每个链接。

(function() {
    var current = location.pathname;
    $('#navbar ul li a').each(function() {
        var $this = $(this); 

        // we check comparison between current page and attribute redirection.
        if ($this.attr('href') === current) {
            $this.addClass('active');
        }
    });
})();

1
var cururl = window.location.pathname;
var curpage = cururl.substr(cururl.lastIndexOf('/') + 1);
var hash = window.location.hash.substr(1);
if((curpage == "" || curpage == "/" || curpage == "admin") && hash=="")
{
//$("nav .navbar-nav > li:first-child").addClass("active");
}
else
{
$(".topmenu li").each(function()
{
    $(this).removeClass("active");
});
if(hash != "")
$(".topmenu li a[href*='"+hash+"']").parents("li").addClass("active");
else
$(".topmenu li a[href*='"+curpage+"']").parents("li").addClass("active");
}

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