我有一个像这样的SVG图形:
a::before { content: url(filename.svg); }
当我将鼠标悬停在标签上时,我真的希望SVG更改填充颜色,而不加载新的SVG文件,就像我现在一样:
a:hover::before { content: url(filename_white.svg); }
这可能是使用JavaScript,jQuery或只是我不知道的纯CSS实现的吗?
谢谢。
接受的答案是不正确的,这实际上可以通过应用SVG蒙版和背景颜色的变通方法来实现:
p:after {
width: 48px;
height: 48px;
display: inline-block;
content: '';
-webkit-mask: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%;
mask: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%;
-webkit-mask-size: cover;
mask-size: cover;
}
.red:after {
background-color: red;
}
.green:after {
background-color: green;
}
.blue:after {
background-color: blue;
}
<p class="red">red heart</p>
<p class="green">green heart</p>
<p class="blue">blue heart</p>
你实际上并没有修改SVG DOM本身,你只是改变了背景颜色。这样,您甚至可以使用图像或渐变作为背景。
正如MisterJ所说,this feature is sadly not widely supported。
三年后,对前缀使用的支持已经上升到93%。