我有一个情况下,我必须写内联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 ' }
其他回答
可以通过添加类来实现id,但不能内联。
<style>.hover_pointer{cursor:pointer;}</style>
<div class="hover_pointer" style="font:bold 12pt Verdana;">Hello World</div>
它只有两行,但是您可以在任何地方重用该类。
只能在外部样式表中使用伪类a:hover。因此,我建议使用外部样式表。代码是:
a:hover {color:#FF00FF;} /* Mouse-over link */
你可以在过去的某个时候这样做。但现在(根据同一标准的最新修订,即候选人推荐)你不能这样做了 .
我的问题是,我正在建立一个网站,使用大量的图像图标,必须由不同的图像悬停交换(例如,蓝色的图像变成红色的悬停)。 对此,我提出了以下解决方案:
.container div { width: 100px; height: 100px; background-size: 100px 100px; } .container:hover .withoutHover { display: none; } .container .withHover { display: none; } .container:hover .withHover { display: block; } <p>Hover the image to see it switch with the other. Note that I deliberately used inline CSS because I decided it was the easiest and clearest solution for my problem that uses more of these image pairs (with different URL's). </p> <div class=container> <div class=withHover style="background-image: url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQrqRsWFJ3492s0t0NmPEcpTQYTqNnH188R606cLOHm8H2pUGlH')"></div> <div class=withoutHover style="background-image: url('http://i.telegraph.co.uk/multimedia/archive/03523/Cat-Photo-Bombs-fa_3523609b.jpg')"></div> </div>
我引入了一个包含这对图像的容器。第一个是可见的,另一个是隐藏的(display:none)。当悬停容器时,第一个容器将被隐藏(display:none),第二个容器将再次显示(display:block)。
简单的回答是:你不能。
长话短说:你不应该。
给它一个类名或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>
注意:以上假设有一个头部部分。