How can I overwrite the CSS style for an (already) defined DIV class with nested anchor tags using jQuery?
The HTML:
<div id="main_menu">
<a id="menu_item_articles" href="articles">articles</a>
</div>
The CSS:
#main_menu {
float: left;
padding-top: 10px;
vertical-align: middle;
text-align: center;
width: 500px;
}
#main_menu a {
border: 1px solid #000;
font-weight: bold;
background: #fff;
color: #000;
padding: 7px;
text-decoration: none;
}
#main_menu a:hover {
border: 1px solid #000;
font-weight: bold;
background: #ff9935;
color: #000;
padding: 7px;
text-decoration: none;
}
.selected_menu_item {
background: #ff9935;
color: #000;
}
What I'm trying to do via jQuery:
Edit: Added missing bit of code (pathArray). All it does is get the path based on wether it's my development environment or not.
var pathArray = $(location).attr('p开发者_如何学Pythonathname').split('/');
var selectedMenuItem = (pathArray[1] == 'sitename') ? pathArray[2] : pathArray[1];
$('#menu_item_' + selectedMenuItem).attr('class', 'selected_menu_item');
Basically what I'm trying to achieve is to get the current page URI, split it up, take page name from it and then highlight the associated menu item when the page is done loading (using $(document).ready()).
It seems like the "#main_menu a" definition in my CSS is set in stone and the new style simply won't apply. Any suggestions?
There doesn't appear to be anything wrong with your jQuery code. However, you need to be more specific with your CSS .selected_menu_item
class selector:
#main_menu a.selected_menu_item {
background: #ff9935;
color: #000;
}
Otherwise its background color will just be overridden by what's in #main_menu a
because that, with the ID selector on your <div>
, is more specific than a class selector alone. That's why it appears as if your class styles aren't being applied.
Check out this example. I am doing something similar here:
http://bobcravens.com/demos/vertical_tabs/script.html
Hope that helps get you started.
Bob
I would suggest doing this in the server-side code. If you are loading a different page anyways, it is worth not waiting for javascript to do the work for you. And it would make the page work better in the case that javascript is disabled.
精彩评论