Добавить активный класс навигации на основе URL-адреса
Я пытаюсь добавить класс 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, который я помещаю в свой тег head в мастере своего сайта. Что я делаю не так?
$(document).ready(function () {
$(function () {
$('li a').click(function (e) {
e.preventDefault();
$('a').removeClass('active');
$(this).addClass('active');
});
});
});
Ответы
Ответ 1
Причина, по которой это не работает, заключается в том, что выполняется 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');
}
})
})
Есть некоторые случаи, когда это не будет работать (несколько похожих ссылок), но я думаю, что это может сработать для вас.
Ответ 2
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>
Ответ 3
Версия 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'))
})
Ответ 4
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");
}
Ответ 5
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');
}
});
})();
Ответ 6
$(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')
});
});
Ответ 7
Это отлично сработало для меня.
$(function($) {
let url = window.location.href;
$('nav ul li a').each(function() {
if (this.href === url) {
$(this).addClass('active');
}
});
});
Ответ 8
Если вашему меню нужно добавить active
класс в li
, вам нужно использовать этот код выше.
$(function($) {
let url = window.location.href;
$('nav ul li a').each(function() {
if (this.href === url) {
$(this).closest('li').addClass('active');
}
});
});
Ответ 9
$(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');
}
})
});
Ответ 10
$(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');
}
})
})
Этот код работает правильно на других страницах, но при переходе на первую страницу все ссылки становятся активными.
Ответ 11
Этот код на странице JS на 100% работает, поставьте свой идентификатор и наслаждайтесь им.
<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')
}
});
});
Ответ 12
Это должно сделать вашу работу: document.querySelector(a[href^='${location.pathname.split('/'[1])}']
).className = 'active'
Ответ 13
Ни одно из вышеперечисленных решений не помогло мне. Наконец это решение 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 - это идентификатор navbar div.
.active класс определяется как:
#premier-topnav .active {
color: brown;
}
Ответ 14
Я знаю, это было довольно давно, этот вопрос был задан. Вот ответ, который будет работать без jQuery:
var activeNavlink = document.querySelectorAll('nav a[href^="/' + location.pathname.split("/")[1] + '"]');
activeNavlink[0].classList.add('active');
Надеюсь, это поможет.
Ответ 15
С 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";
}
}
})();