简体   繁体   English

在JavaScript中应用CSS会覆盖悬浮链接样式吗?

[英]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. 我有一些JavaScript可以正确更改图像,但是一旦调用它,我的a:hover CSS代码将不再起作用。

Looking with firebug the following JavaScript creates this css rule: 使用firebug查找以下JavaScript创建此css规则:

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? 如何应用JavaScript,并且没有让element.style规则覆盖a:hover代码?

As far as I know setting the element.style.backgroundImage is essentially the same as using an inline style. 据我所知,设置element.style.backgroundImage本质上与使用嵌入式样式相同。

<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. 正如丹尼尔·怀特(Daniel White)所说,jQuery在这里将非常有用。 Although you may be able to get around this issue in two ways. 尽管您可以通过两种方式解决此问题。

One, Generate the style using javascript to write a style tag 一,使用JavaScript生成样式以编写样式标签

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 或两个,手动设置mouseenter / mouseleave事件以处理您的悬停样式

Update 更新资料

or three, as pointed out by KevinUK, use the !important css tag to override the inline style set. 就像KevinUK指出的那样,请使用或使用三个!important css标记来覆盖内联样式集。

<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 我对此CSS js样式的差距也感到沮丧,因此我建立了
methods to apply style from js with a CSS string 使用CSS字符串从JS应用样式的方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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