简体   繁体   中英

How to change class named active into link's active attribute in javascript

I'm using superfish for menu.Since it doesn't come with active class to denote current page tab.I added the following javascript.

<script type="text/javascript">
var path = window.location.pathname.split('/');
path = path[path.length-1];
if (path !== undefined) {
  $("ul.sf-menu")
    .find("a[href$='" + path + "']") // gets all links that match the href
    .parents('li')  // gets all list items that are ancestors of the link
    .children('a')  // walks down one level from all selected li's
    .addClass('active');
}
</script>

I also added a class named active in css as the script requires.

.sf-menu a.active{
   margin-top:-5px;
   height: 51px; 
   padding-top: 15px;
   z-index: 100;
   background-color:#072438;
 }

It worked just fine.However for some reason I would like to change the css from

a.active into a:active

But how do I change this part in javascript to suit the css please?

.addClass('active');

You can't add a pseudo-class on an element using javascript in the same way that you can't add a pseudo-class in an inline style='' attribute.

What you can do is alter your stylesheet with javascript to add the rule you want:

document.styleSheets[0].insertRule('a:active { color: red; }' , 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM