我有一个这样的 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://gh.max.ax/heart.svg) no-repeat 50% 50%;
mask: url(https://gh.max.ax/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 .罢工>
时隔六年,对前缀使用的支持上升到97% .
关于javascript - 更改 :before or :after CSS 中的 SVG 填充颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40019456/