突出显示导航栏中的当前页面
我试图解决主题行中提出的问题。 以下是我想要完成的HTML和jQ。
HTML
JQ
//Menu highlights. $(document).ready(function(){ var pathname = (window.location.pathname.match(/[^\/]+$/)[0]); $(".topnav1 li a").each(function() { if ($(this).attr('href')==pathname) { $("li.highlight").removeClass("highlight"); $(this).parent().parent().addClass("highlight"); } }); $("li.highlight"').parents().each(function(){ if ($(this).is("li")){ $(this).addClass("highlight"); } }); });
我们的想法是从默认列表项中删除突出显示的类,并将其分配给其href属性与当前URL匹配的列表项。 我必须承认我不是最好的编程匹配模式,所以我有点不知道如何只匹配部分url与href属性,我不知道这就是为什么我的代码不是工作(突出显示保留在主菜单项上,不适用于其他菜单项)。 有任何想法吗?
我建议如下:
// in real life use: var curURL = document.location.toString(); var curURL = 'http://fihttps://stackoverflow.com/questions/8479513/highlight-current-page-in-navigation-bar/ddle.jshell.net/_display/testimonials_page.php'; $('.topnav1 li.highlight').removeClass('highlight'); $('.topnav1 li a').each( function(){ if (curURL.indexOf(this.href) != -1){ $(this).closest('li').ahttps://stackoverflow.com/questions/8479513/highlight-current-page-in-navigation-bar/ddClass('highlight'); } });
JS小提琴演示 。
参考文献:
-
JavaScript, Mozilla Developer Network的JavaScript资源:
-
document.location
。 -
document.URL
。 -
indexOf()
。 -
toString()
。
-
-
jQuery,来自jQuery API :
-
ahttps://stackoverflow.com/questions/8479513/highlight-current-page-in-navigation-bar/ddClass()
。 -
closest()
。 -
each()
。 -
removeClass()
。
-
通过执行以下操作,您可以获得相同的结果:
var filename = window.location.pathname.match(/[^\/]+$/)[0]; $('li.highlight').removeClass('highlight'); $('ul.topnav1 li a[href="' + filename + '"]').parents('li').ahttps://stackoverflow.com/questions/8479513/highlight-current-page-in-navigation-bar/ddClass('highlight');
既然你可以使用jQuery属性选择器,你可以做一个严格的检查,让jQuery完成工作, tag[attribute="value"]
这对我有用:
var domain = '{{ DOMAIN }}'; // www.example.com or dev.example.com var domain_index = window.location.href.indexOf(domain); var long_app_name = window.location.href.slice(domain_index+domain.length+1); // this turns http://www.example.com/whatever/whatever to whatever/whatever app_name = long_app_name.slice(0, long_app_name.indexOf('/')); //now you are left off with just whatever
然后你使用jquery来添加类active
$(’nav a [href * =“’+ app_name +’”]’)。nearest(’li’)。ahttps://stackoverflow.com/questions/8479513/highlight-current-page-in-navigation-bar/ddClass(’active’);
当然还有css:
.active{background:red;}
这有用,如果你有这样的HTML:
如果您在www.somesite.com/https://stackoverflow.com/questions/8479513/highlight-current-page-in-navigation-bar/ee thaen https://stackoverflow.com/questions/8479513/highlight-current-page-in-navigation-bar/ee是'app'并且它将处于活动状态,这将使用页面URL自然地添加类活动并将您的背景颜色设置为红色