开发者

Adding css properties to jquery element has different result - class vs. css() method

开发者 https://www.devze.com 2023-03-08 08:56 出处:网络
For my site, I\'m saving the navigation menu\'s selected name in a cookie and after postback I read the cookie and then apply a background image to that selected menu item (using the same image I use

For my site, I'm saving the navigation menu's selected name in a cookie and after postback I read the cookie and then apply a background image to that selected menu item (using the same image I use for hovering).

I made a class for my "selected" menu items:

.selected
 {
color: Green;
height: 40px;
background: url(images/menu_hover.jpg) bottom no-repeat; 
 }

When I开发者_运维问答 check for a cookie after postback I want to apply this class:

$("#" + $.cookie(cookieName)).addClass("selected");

It seems it only applies the background image, not the color or the height. In order to have the color and height work at all, I have to explicitly set those using the .css() method:

$("#" + $.cookie(cookieName)).css({ 'color': "green" });
$("#" + $.cookie(cookieName)).css({ 'height': "40px" });

Just curious if anyone has an idea as to why this occuring?


It sounds to me like a css specificity issue -- you may have color and height defined elsewhere with a more specific selector.


May it be that other CSS selectors match your element as well and they have higher priority?

You may find more info here: CSS: Understanding the selector's priority / specificity


Use something like the Web Developer toolbar or DOM Inspector in Firefox to work out what's actually affecting your styles.


It sound like you want to use a class on a specific link when your on that page, so you could have a class on the body, like so:

<body class="home">

And in your CSS:

.home a.homeLink:link{
...
}

Wouldn't need JS at all then.

Done an example here:

http://jsfiddle.net/NbVVr/

Not sure if this is what you want?

0

精彩评论

暂无评论...
验证码 换一张
取 消