我有一个情况下,我必须写内联CSS代码,我想应用悬停样式的锚。
我如何使用一个:悬停在内联CSS内的HTML样式属性?
例如,你不能可靠地在HTML电子邮件中使用CSS类。
我有一个情况下,我必须写内联CSS代码,我想应用悬停样式的锚。
我如何使用一个:悬停在内联CSS内的HTML样式属性?
例如,你不能可靠地在HTML电子邮件中使用CSS类。
当前回答
你可以做到的。但不是内联样式。你可以使用onmouseover和onmouseout事件:
<div style="background: #333;填充:10 px;光标:指针” onmouseover = " this.style.backgroundColor =“# 555”;“onmouseout = " this.style.backgroundColor =“# 333”;" > 在我身上盘旋! < / div >
其他回答
它不是内联CSS,但它是内联的。
<a href=“abc.html” onMouseOver=“this.style.color='#0F0'” onMouseOut=“this.style.color='#00F'”>Text</a>
使用JavaScript:
a)增加内联样式
document.head.insertAdjacentHTML('beforeend', '<style>#mydiv:hover{color:red;}</style>');
B)或者更难一点的方法——添加“鼠标悬停”
document.getElementById("mydiv").onmouseover= function(e){this.className += ' my-special-class'; };
document.getElementById("mydiv").onmouseleave= function(e){this.className = this.className.replace('my-special-class',''); };
注意:JavaScript中的多词样式(即font-size)是一起编写的:
element.style.fontSize="12px"
我的问题是,我正在建立一个网站,使用大量的图像图标,必须由不同的图像悬停交换(例如,蓝色的图像变成红色的悬停)。 对此,我提出了以下解决方案:
.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)。
虽然“你不应该”的上下文可能适用,但可能在某些情况下你仍然想实现这一点。我的用例是根据一些数据值动态设置悬停颜色,以实现只有CSS可以受益于特异性。
只使用CSS
CSS
/* Set your parent color for the inherit property */
.sidebar {
color: green;
}
/* Make sure your target element "inherit" parent color on :hover and default */
.list-item a {
color: inherit
}
.list-item a:hover {
color: inherit
}
/* Create a class to allows to get hover color from inline style */
.dynamic-hover-color:not(:hover) {
color: inherit !important;
}
然后你的标记会像这样:
标记
<nav class="sidebar">
<ul>
<li class="list-item">
<a
href="/foo"
class="dynamic-hover-color"
style="color: #{{category.color}};"
>
Category
</a>
</li>
</ul>
</nav>
我用把手来做这个例子,但想法是你采取任何方便你的用例来设置内联样式(即使它是手动写你想要的悬停颜色)
这是不可能的。您可以选择使用JavaScript或CSS块。
也许有一些JavaScript库可以将私有样式属性转换为样式块。但是这样代码就不符合标准了。