添加基于URL的活动导航类

sly*_*itz 20 javascript css menu

我正在尝试根据页面加载后的页面,将"活动"类(即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>
Run Code Online (Sandbox Code Playgroud)

这是我在我的网站主文件中放入头标记的javascript示例.我究竟做错了什么?

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

Rob*_* M. 49

这不起作用的原因是因为javascript正在执行,然后页面正在重新加载,这使"活动"类无效.您可能想要做的是:

$(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');
        }
    })
})
Run Code Online (Sandbox Code Playgroud)

在某些情况下,这将不起作用(多个类似的尖头链接),但我认为这可能对你有用.


Fig*_*Ali 13

    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');
      }
     });
    });
Run Code Online (Sandbox Code Playgroud)
.active, a.active {
    color: red;
}
a {
    color: #337ab7;
    text-decoration: none;
}
li{
    list-style:none;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


Pan*_*ris 8

使用 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";
        }
    }
})();
Run Code Online (Sandbox Code Playgroud)

  • 工作完美,只是它删除了“a”元素中的所有现有类以支持“is-active”。为了解决这个问题,我将代码片段中的第 7 行更改为 `menuItems[i].className += " is-active";` ,这似乎已经成功了。 (3认同)

Ser*_*liy 5

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'))
})
Run Code Online (Sandbox Code Playgroud)