简体   繁体   中英

Applying css with javascript overrides hover link style?

I have some JavaScript which is changing an image correctly but once it has been called, my a:hover CSS code no longer works.

Looking with firebug the following JavaScript creates this css rule:

element.style {
background-image:url(/content/images/side_partnershipsOver.png);
}

document.getElementById('partnerships').style.backgroundImage = "url(/content/images/side_partnershipsOver.png)";

How can I apply the JavaScript and not have the a:hover code overriden by the element.style rule?

As far as I know setting the element.style.backgroundImage is essentially the same as using an inline style.

<style type="text/css">
  a { background: blue; }
  a:hover { background:green; }
</style>
<a href="#" style="background:red;">link<a>

Unfortunately the inline style always wins. In the above sample the link will always be red. As Daniel White said jQuery would be very useful here. Although you may be able to get around this issue in two ways.

One, Generate the style using javascript to write a style tag

document.write("<style type='text/css'>#partnerships { background-image:url(/content/images/side_partnershipsOver.png);}</style>");

or two, Manually setup mouseenter/mouseleave events to handle your hover style

Update

or three, as pointed out by KevinUK, use the !important css tag to override the inline style set.

<style type="text/css">
  a { background: blue; }
  a:hover { background:green !important; }
</style>
<a href="#" style="background:red;">link<a>

I was also frustrated about this CSS js style gap so I build
methods to apply style from js with a CSS string

elm.jCSS(cssText);elm.jCSSPseudo(cssText,pseudoElt)

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