简体   繁体   中英

Links lose their css background-color hover attribute when changing background with jQuery

I've got a menu like this one :

<ul id="menu">
    <li><a href="#" id="test">test</a></li>
    <li><a href="#" id="test2">test2</a></li>
</ul>

and css :

#menu li a:link {
background: transparent;
}

#menu li a:hover {
background-color: red;
}

At some point in my code I need to make the background of the links transparent again, so I make a :

$("#menu > li > a:link").css("background","transparent");

Which works but after that, my problem is that it seems to wipe the background-color attribute of the css hover. Indeed when I hover the links again nothing happens. If that helps when I add color:blue in the #menu li a:hover css, the text is blue when I hover but still no background-color.

I figured out a way to do the hover with jQuery but I would prefer to do it with css since in my opinion that's how it should be. Is it a bug ? Is there any way to make the background transparent without wiping the hover css ?

Thanks in advance,

Nolhian

I had this same problem, and my solution was to make two separate classes rather than change the background color in jquery.

a.default:hover {  background-color: red; }
a.hovered:hover {  background-color: transparent; }  

$("#menu > li > a:link").removeClass("default");
$("#menu > li > a:link").addClass("hovered");

No, the problem is with your CSS and the fact it's being overwritten. Change:

 a:hover {background-color: yellow; }

to this:

 a:hover {background-color: yellow!important; }

Then it will work properly.

Target the background color directly, instead of simply "background":

#menu li a:link {
background-color: transparent;
}


$("#menu > li > a:link").css("background-color","transparent");

您可以执行“ onmouseover” javascript悬停。

It's just a side effect of how CSS works. The :hover pseudo-class must be declared AFTER the :link pseudo-class. Changing :link will reset :hover, so you need to reset your :hover as well. One way to avoid this would be to move your CSS that alters the color from its initial setting into a class:

a:link {background-color: transparent; }
a:hover {background-color: yellow; }
a.myClass:link {background-color: cyan; }

And then

$("#menu > li > a:link").addClass("myClass");

And later

$("#menu > li > a:link").removeClass("myClass");

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