导航根据链接给背景

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">
  
 
<ul>
 
<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>
 
    </ul>
 
  
</menu>

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

#nav {
   margin:200px auto;
   width:430px;
   }
 
#nav ul {
   list-style:none;
   background-color:#64abfb;
   }
 
#nav ul li {
   display:inline-block;
   line-height:44px;
   }
 
#nav ul li a {
   margin:10px;
   color:#FFF;
   padding:4px;
   font-size:20px;
   text-decoration:none;
   }
 
#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
.lastIndexOf("/")+1);
     $("#nav ul li a").each(function(){
          if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
          $(this).addClass("active");
     })
});

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) {
      aObj[i].className='active';
    }
  }
}
 
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;
}

http://webdesignerhut.com/active-class-navigation-menu/

THE END
分享
二维码
打赏
< <上一篇
下一篇>>