使用CSS在悬停时转换SVG路径的fill属性 [英] Using CSS to transition the fill property of an SVG path on hover

查看:1146
本文介绍了使用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; }

这里有一个工作 JSFiddle

或者,内联可以更方便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).

这篇关于使用CSS在悬停时转换SVG路径的fill属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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