---- AI试用 ---域名问题某些图片和js资源无法访问,导致一些代码实例无法运行!(代码里gzui.net换成momen.vip即可)


前端开发 蚂蚁 2938℃ 0评论

When we’re creating a navigation menu for a website, it’s always good to make it so the visitors or user on the website knows on which page or part of the site he is on. This can be accomplished by adding an “active class” or “current class” to the menu item that links to the page on which the visitor or user is.
To do this, we’ll create a css navigation menu. With a few links in it just for demonstration. Of course you can add as many as you want.

<menu id="nav">
<li><a href="active.html">Home</a></li>
<li><a href="active1.html">Contact</a></li>
<li><a href="active2.html">About</a></li>
<li><a href="active3.html">Portfolio</a></li>

Then we add some style to it to make it look like an actual navigation menu.

#nav {
   margin:200px auto;
#nav ul {
#nav ul li {
#nav ul li a {
#nav ul li a:hover {
   border-bottom:3px #FFF solid;
#nav ul li .active {
   border-bottom:3px #FFF solid;

Now, you see a class named #nav ul li .active this is not yet added to any of the navigation items. To add it, we need to add some jQuery to our project, that will check the page URL that the user or visitor is viewing, and compares with the one on the menu item. If they mach, it’ll add the .active class to that menu item.

$(function() {
     var pgurl = window.location.href.substr(window.location.href
     $("#nav ul li a").each(function(){
          if($(this).attr("href") == pgurl || $(this).attr("href") == '' )

Or, if u want to do it by plain javascript, you can do that too. Here’s how.

First you got to add a #nav ID to your<nav> element. Then, use this code to add the active class to the li a element.

function setActive() {
  aObj = document.getElementById('nav').getElementsByTagName('a');
  for(i=0;i&amp;lt;aObj.length;i++) {
    if(document.location.href.indexOf(aObj[i].href)&amp;gt;=0) {
window.onload = setActive;

Active Class for WordPress

Incase your WordPress Theme doesn’t support it yet, you can add the following script to your functions.php and use the .active CSS Class to style the current navigation item.

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class($classes, $item){
     if( in_array('current-menu-item', $classes) ){
             $classes[] = 'active ';
     return $classes;


转载请注明:有爱前端 » 导航根据链接给背景

喜欢 (0)or分享 (0)