我有一个情况下,我必须写内联CSS代码,我想应用悬停样式的锚。
我如何使用一个:悬停在内联CSS内的HTML样式属性?
例如,你不能可靠地在HTML电子邮件中使用CSS类。
我有一个情况下,我必须写内联CSS代码,我想应用悬停样式的锚。
我如何使用一个:悬停在内联CSS内的HTML样式属性?
例如,你不能可靠地在HTML电子邮件中使用CSS类。
当前回答
下面是最好的代码示例:
<一个 Style =" font - family:宋体;font - family:宋体;" href = " http://aashwin.com/index.php/education/library/ " onmouseover = " this.style.color = # 0 f0” onmouseout = " this.style.color = # 00 f”> 图书馆 < / >
主持人建议:保持关注点的分离。
超文本标记语言 <一个 Style =" font - family:宋体;font - family:宋体;" href = " http://aashwin.com/index.php/education/library/ " 类= " lib-link " > 图书馆 < / >
JS
const libLink = document.getElementsByClassName("lib-link")[0]; //数组0假设只有一个链接, //你将不得不循环或使用事件委托为多个 //但我们不会在这里深入讨论 libLink。Onmouseover = function () { this.style.color = ' # 0 f0 ' } libLink。Onmouseout = function () { this.style.color = ' # 00 f ' }
其他回答
只能在外部样式表中使用伪类a:hover。因此,我建议使用外部样式表。代码是:
a:hover {color:#FF00FF;} /* Mouse-over link */
下面是最好的代码示例:
<一个 Style =" font - family:宋体;font - family:宋体;" href = " http://aashwin.com/index.php/education/library/ " onmouseover = " this.style.color = # 0 f0” onmouseout = " this.style.color = # 00 f”> 图书馆 < / >
主持人建议:保持关注点的分离。
超文本标记语言 <一个 Style =" font - family:宋体;font - family:宋体;" href = " http://aashwin.com/index.php/education/library/ " 类= " lib-link " > 图书馆 < / >
JS
const libLink = document.getElementsByClassName("lib-link")[0]; //数组0假设只有一个链接, //你将不得不循环或使用事件委托为多个 //但我们不会在这里深入讨论 libLink。Onmouseover = function () { this.style.color = ' # 0 f0 ' } libLink。Onmouseout = function () { this.style.color = ' # 00 f ' }
在当前的CSS迭代中不支持内联伪类声明(不过,据我所知,在未来的版本中可能会支持)。
现在,你最好的办法可能是直接在你想要样式的链接上方定义一个样式块:
<style type="text/css">
.myLinkClass:hover {text-decoration:underline;}
</style>
<a href="/foo" class="myLinkClass">Foo!</a>
简单的回答是:你不能。
长话短说:你不应该。
给它一个类名或id,并使用样式表应用样式。
:hover是一个伪选择器,对于CSS来说,它只在样式表中有意义。没有任何内联样式的对等物(因为它没有定义选择标准)。
回应行政长官的评论:
关于动态添加CSS规则的好脚本,请参阅完全Pwn CSS with Javascript。关于这个主题的一些理论,请参见Change样式表。
另外,不要忘记,如果可以的话,还可以添加到外部样式表的链接。例如,
<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>
注意:以上假设有一个头部部分。
你不能完全按照你描述的去做,因为a:hover是选择器的一部分,而不是CSS规则。样式表有两个组件:
selector {rules}
内联样式只有规则;选择器隐式为当前元素。
选择器是一种表达性语言,它描述了一组匹配类xml文档中的元素的标准。
然而,你可以接近,因为从技术上讲,一个风格集几乎可以去任何地方:
<html>
<style>
#uniqueid:hover {do:something;}
</style>
<a id="uniqueid">hello</a>
</html>