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

查看:26
本文介绍了使用 CSS 在悬停时转换 SVG 路径的填充属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的页面上的 object 标记中包含一个 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>

有问题的图像是一张世界地图,当鼠标悬停在 group 上时,我想转换 fill 属性,在这种情况下,我对我的 SVG 进行了分组按大陆,所以南美洲看起来像这样:

The image in question is 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>

我可以通过在我的 SVG 文档顶部使用以下 CSS 使 fill 属性在悬停时更改:

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 过渡淡入,颜色会立即改变,有人能解释一下吗?

But I can't get the fill colour to fade in with a CSS transition, the colour just changes instantly, can anyone shed light on this please?

推荐答案

为了过渡/淡入淡出,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.

或者,内联更方便(style=""):

Or, doing it inline can be more convenient (style=""):

<path style="fill: #FAFAFA;" d="..."/>

为了让 CSS 进行淡入淡出,它需要处理 CSS/内联样式中的开始和结束值(而不是使用 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 路径的填充属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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