添加基于 URL 的活动导航类

Add Active Navigation Class Based on URL

本文关键字:活动 导航 URL 添加      更新时间:2023-09-26

我正在尝试添加一个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');
        });
    });
});

这不起作用的原因是因为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');
        }
    })
})

在某些情况下,这不起作用(多个类似的指向链接(,但我认为这可能对您有用。

    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>

使用 VANILLA plain 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";
        }
    }
})();

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'))
})

如果您的菜单需要在 li 中添加 active 类,则需要使用上面的代码。

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

以上解决方案都不适合我。最后,这个JavaScript解决方案奏效了。

<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 是 Navbardiv 的 ID。
.active 类定义为:

#premier-topnav .active {
    color: brown;   
}
$(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')
        });
    });

页面上的这个JS代码是一个100%的工作把你的ID放进去享受它。

   <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')
                  }
            });
   });

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");
}

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');
        }
    });
})();

对我来说非常有效。

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

我知道这个问题被问了很长时间。这是在没有jQuery的情况下可以工作的答案:

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

希望这有帮助。

如果你想在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>

谢谢

这应该在一个衬里完成你的工作。

document.querySelector(`a[href^='${location.pathname.split('/'[1])}']`).className = 'active'

jQuery style:

$('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({
我知道

这是迟到的答案,但这对我来说还可以

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')
    }
}
$(function(){
//this returns the whole url
  var current = window.location.href;
  //this identifies the list you are targeting
  $('#nav li a').each(function(){
    var $this = $(this);
    // if the current path is exactly like this link, make it active
    if($this.attr('href') === current){
    //this takes care of ul inside a ul, it opens and make active the selected li
        $this.parents('.dropdown-menu').toggle();
        $this.css('color', 'red');
    }
  })
});

如果页面也有任何查询字符串参数,则下面的 jquery 脚本将匹配 manu。此脚本对于名称几乎相同的链接非常有用。

<script>
        //select current menu Item
        $(function () {
            var current = location.pathname.toLocaleLowerCase();
            $('.sidebar li a').each(function () {
                var $this = $(this);
                var href = $this.attr('href');
                href = href.replace(/'?.*/, "").toLocaleLowerCase();
                // if the current path is equal to this link, make it active
                if (href === current) {
                    $this.addClass('active');
                }
            })
        })
    </script>

可访问版本:

这是一个受 rob 启发的可访问版本。

  1. 我不想在主页上运行这个脚本,所以我检查它是否是主页
  2. 我检查链接是否与确切的页面匹配,而不是检查它是否包含在路径中。否则,您将在查询中获得多个项目。

.JS

function activateCurrentPage(menuItems){
    var current = location.pathname;
    if (current !== "/") {
    menuItems.each(function(){
        var $this = $(this);
        if($this.attr('href') === current){
            $this.addClass('active');
            $this.attr('aria-current', 'page');
        }
    });
    };  
}
activateCurrentPage( $('#nav li a') );  

.CSS

然后对于 CSS,不要以活动类为目标,而是以 aria 属性为目标。

#nav a[aria-current="page"]{
   color:red;
}

看到一些普通的Javascript。https://www.youtube.com/watch?v=BI3kNsTruWo&ab_channel=OnlineTutorials把它放在我的Wordpress网站标题后面的<script>标签中

(function () {
  const currentLocation = location.href;
  console.log(currentLocation);
  const menuItem = document.getElementsByClassName('nav-item');
  const menuLength = menuItem.length
    for ( i = 0; i < menuLength; i++){
    if(menuItem[i].href === currentLocation){
      menuItem[i].className += " active"
    }
}
})();
        <a class="nav-item" href="/ideja/">Ideja</a>
        <a class="nav-item" href="/piesaki-sapni/">Piesaki Sapni</a>
        <a class="nav-item" href="/uznemejiem/">Uzņēmējiem</a>
        <a class="nav-item" href="/sapnu-banka/">Sapņu banka</a>
        <a class="nav-item" href="/sapnus-atbalsta/">Sapņus atbalsta</a>
        <a class="nav-item" href="/99-iedvesmas-stasti/">99 iedvesmas stāsti</a>
        <a id="lv" class="active" href="#">LV</a>
        <a href="javascript:void(0);" class="icon" onclick="openNavbar()">
            <div id="hamburger" class="hamburger "></div>
        </a>

在使用 Networker 的示例时,如果选择了任何页面,则指向根的链接会亮起,我遇到了麻烦。 这将防止根 PAE 出现这种情况:

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;

为我完成了工作...把它放在身体标签的结尾之前

 $(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');
                }
            })
        }
    })

类可以使生活更轻松。

.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;
        }
    }
})();
以下是将

动态活动类添加到导航栏元素的解决方案。

// 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)
    });
 });

要在 .net MVC 项目中导航栏上的 li 标记上动态添加活动类,其中仪表板在 url 中只有/,您可以尝试以下操作:

.HTML

<ul class="nav">
<li class="nav-item">
    <a class="nav-link" href="/">
        
        <i class="icon-grid menu-icon"></i>
        <span class="menu-title">Home</span>
    </a>
</li>
<li class="nav-item">
    <a class="nav-link" href="/Home/About">
        <i class="icon-monitor menu-icon"></i>
        <span class="menu-title">About</span>
    </a>
</li>
</ul>

.JS

<script>
        $(() => {            
            // Get the current URL path and remove the trailing slash if it exists
            var currentPath = window.location.pathname.replace(/'/$/, '');
            // Loop through each "nav-link" element
            $('.nav-link').each(function () {
                // Get the href attribute of the link and remove the trailing slash if it exists
                var linkPath = $(this).attr('href').replace(/'/$/, '');
                // Check if the current path matches the link path
                if (currentPath === linkPath) {
                    // Add the "active" class to the parent "nav-item" element
                    $(this).closest('.nav-item').addClass('active');
                }
            });
        })
    </script>