在 :before 或 :after CSS 中更改 SVG 填充颜色 [英] Change SVG fill color in :before or :after CSS

查看:68
本文介绍了在 :before 或 :after CSS 中更改 SVG 填充颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样放置的 SVG 图形:

I have a SVG graphic put like this:

a::before { content: url(filename.svg); }

当我将鼠标悬停在标签上时,我真的希望 SVG 改变填充颜色,而不像我现在那样加载新的 SVG 文件:

When I hover over the tag, I really want the SVG to change the fill color, without loading a new SVG file, as I have now:

a:hover::before { content: url(filename_white.svg); }

这是否可以使用 JavaScript、jQuery 或我不知道的纯 CSS 来实现?

Is this possible to achieve using JavaScript, jQuery or just pure CSS that I am not aware of?

谢谢.

推荐答案

使用 content 属性生成(非公开)标记,其功能与 元素中的 svg 等效.

Using the content property generates (non-exposed) markup functionally equvialent to an svg in an <img> element.

您不能将样式应用于 svg 文档中的元素,因为:

You cannot apply style to elements inside the svg document because:

  1. 样式不允许跨文档级联
  2. 当使用 <img>(或 content,或任何引用 svg 的 css 图像属性)时,出于安全考虑,浏览器不会公开 svg 文档
  1. styles are not allowed to cascade across documents
  2. when using <img> (or content, or any css image property that references svg) the svg document is not exposed by the browsers due to security concerns

类似的问题,但针对 background-image 此处此处.

Similar questions, but for background-image here and here.

因此,要做您想做的事,您必须以某种方式解决上述两点.这样做有多种选择,例如使用内联 svg、使用过滤器(应用于 )或生成不同的 svg 文件(或数据 URI),如您的问题.

So, to do what you want you must get around the two points above somehow. There are various options for doing that, e.g using inline svg, using filters (applied to the <img>) or generating different svg files (or data URIs), as in your question.

这篇关于在 :before 或 :after CSS 中更改 SVG 填充颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆