How to write a:hover in inline CSS?

I have a case where I must write inline CSS code, and I want to apply a hover style on an anchor.

How can I use a:hover in inline CSS inside the HTML style attribute?

Eg you can't reliably use CSS classes in HTML emails.


Short answer: you can't.

Long answer: you shouldn't.

Give it a class name or an id and use stylesheets to apply the style.

:hover is a pseudo-selector and, for CSS, only has meaning within the style sheet. There isn't any inline-style equivalent (as it isn't defining the selection criteria).

Response to the OP's comments:

See Totally Pwn CSS with Javascript for a good script on adding CSS rules dynamically. Also see Change style sheet for some of the theory on the subject.

Also, don't forget, you can add links to external stylesheets if that's an option. For example,

<script type="text/javascript">
  var link = document.createElement("link");
  link.setAttribute("rel","stylesheet");
  link.setAttribute("href","http://wherever.com/yourstylesheet.css");
  var head = document.getElementsByTagName("head")[0];
  head.appendChild(link);
</script>

Caution: the above assumes there is a head section.


您可以通过在onMouseOveronMouseOut参数中使用JavaScript更改样式来获得相同的效果,但如果您需要更改多个元素,则效率极低:

<a href="abc.html"
   onMouseOver="this.style.color='#0F0'"
   onMouseOut="this.style.color='#00F'" >Text</a>

More accurate to say, you could do it at some point in the past. But now (according to the latest revision of the same standard, which is Candidate Recommendation) you can't ...

链接地址: http://www.djcxy.com/p/15780.html

上一篇: display:inline和display:inline之间的区别是什么?

下一篇: 如何写一个:悬停在内联CSS?