Javascript 将 :hover 用于元素的内联样式(使用 HTML/CSS/php)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5113775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:42:53  来源:igfitidea点击:

Using :hover for an element's inline style (using HTML/CSS/php)

phpjavascripthtmlcsshover

提问by Jared

Possible Duplicates:
How do I embed an “a:hover{…}” rule into a style attribute in the middle of a document?
How to write a:hover in inline CSS?

可能的重复项:
如何将“a:hover{…}”规则嵌入到文档中间的样式属性中?
如何在内联 CSS 中编写 a:hover?

I want to dynamically change the hover colour of an element, but not using external CSS stylesheets, only inline. This is the code (using php to generate the element)

我想动态更改元素的悬停颜色,但不使用外部 CSS 样式表,仅内联。这是代码(使用php生成元素)

echo '
<div class="container" style="color:#'.$color.'">
  '.$contents.'
</div>';

When the user hovers over this container element, the color style will change to the value of $color(at the moment there is no hovering).

当用户将鼠标悬停在此容器元素上时,颜色样式将更改为值$color(此时没有悬停)。

Any help would be appreciated.

任何帮助,将不胜感激。

采纳答案by Sujeet

This will help you if javascript is appreciable

如果 javascript 是可观的,这将对您有所帮助

<TD onMouseOver="this.bgColor='#00CC00'" onMouseOut="this.bgColor='#009900'" bgColor=#009900>
<A HREF="http://www.mysite.com">Click Here</A></TD>

or

或者

Javascript Change Hyperlink Text Color Onmouseover

Javascript 在鼠标悬停时更改超链接文本颜色

<style type="text/css">

a {
font-weight:bold;
font-family:verdana;
text-decoration:none;
}

</style>

<script type="text/javascript" language="javascript">
function changeColor(idObj,colorObj)
{
    document.getElementById(idObj.id).style.color = colorObj;
}
</script>

<a href="#" style="color: #000000" onmouseover="this.style.color='#FF0000'" onmouseout="this.style.color='#000000'">
    Link 1</a>
<br />
<br />
<a href="#" style="color: #999999" onmouseover="this.style.color='#008000'" onmouseout="this.style.color='#999999'">
    Link 2</a>
<br />
<br />
<a href="#" style="color: #FF0000" onmouseover="this.style.color='blue'" onmouseout="this.style.color='#FF0000'">
    Link 3</a>
<br />
<br />
<a id="lnk1" href="#" style="color: #008000" onmouseover="changeColor(this,'#FF0000');"
    onmouseout="changeColor(this,'#008000');">Link Color change using javascript function</a>

回答by Russell Dias

You can't, since you can't set the pseudo-selectors inline. Ideally, you should design separate classes in your external css which would represent the various hover states you need, and in PHP assign these classes to your content.

你不能,因为你不能内联设置伪选择器。理想情况下,您应该在外部 css 中设计单独的类来代表您需要的各种悬停状态,并在 PHP 中将这些类分配给您的内容。