使用CSS在悬停时转换SVG路径的fill属性
我在一个对象
标签中包含一个SVG图片文件,如下所示:
I'm including an SVG image file on my page within an object
tag, like this:
<object type="image/svg+xml" data="linkto/image.svg">
<!-- fallback image in CSS -->
</object>
有问题的图片是世界地图,我想转换当鼠标悬停在
属性,在这种情况下,我已经将大陆的SVG分组,所以南美洲看起来像这样: 组
上时,填充
The image in question is of a world map, i want to transition the fill
property when the mouse hovers over a group
, in this case I've grouped my SVG by continent, so South America looks something like this:
<g id="south_america">
<path fill="#FAFAFA" d="(edited for brevity)"/>
</g>
我可以获得 fill
在我的SVG文档顶部使用以下CSS:
I can get the fill
property to change on hover by using the following CSS at the top of my SVG document:
<style>
#south_america path {
transition: fill .4s ease;
}
#south_america:hover path {
fill:white;
}
</style>
但我不能得到 fill
为了转换/淡出,CSS需要一个起始值和一个结束值。
因为你使用SVG属性设置路径的颜色 fill = #FAFAFA
,CSS不会处理它,并且转换不会消失。
In order to transition/fade, CSS needs a starting value and an ending value.
Because you set the color for the path using the SVG attribute fill="#FAFAFA"
, CSS doesn't process it and the transition doesn't fade.
如果使用CSS设置颜色,
Instead if you use CSS to set the color, the transition will behave as expected
所有我必须做的转换工作是给 #europe
从
So all I had to do to make the transition work is give the #europe
a starting fill to transition from.
path { transition: fill .4s ease; }
/* set fill for before and for during hover */
#europe path { fill: red; }
#europe:hover path { fill: white; }
或者,内联可以更方便c> style =):
Or, doing it inline can be more convenient (style=""
):
<path style="fill: #FAFAFA;" d="..."/>
只是为了让CSS做你的衰落,它需要处理CSS中的开始和结束值/ inline style(与使用SVG fill =
属性相反)。
Just in order for CSS to do your fading, it needs to handle the start and end values in CSS/inline style (as opposed to using the SVG fill=
attribute).