所以我创建了一个包含一些彩色 SVG 图像的页面,我希望它们在正常状态下变灰,并在悬停时显示颜色。
svg {
width: 200px;
margin: 50px;
}
svg * {
transition: fill 1s;
}
svg:not(:hover) * {
fill: gray !important;
}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 3 1">
<rect x="0" y="0" width="1" height="1" style="fill: red" />
<rect x="1" y="0" width="1" height="1" style="fill: green" />
<rect x="2" y="0" width="1" height="1" style="fill: blue" />
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 3 1">
<g>
<rect x="0" y="0" width="1" height="1" style="fill: red" />
<rect x="1" y="0" width="1" height="1" style="fill: green" />
<rect x="2" y="0" width="1" height="1" style="fill: blue" />
</g>
</svg>
正如你所看到的,SVG 有不同颜色的元素,一些元素也是分组的。这是一个非常简单的例子,但真实的图像要复杂得多,有大量的transform
。 -s 所以我不能轻易删除分组。
两张图片效果都很好,并且在悬停时会改变颜色,但第一张图片会立即改变颜色,而第二张图片在动画开始前有 1 秒的延迟。
在搜索解决方案时,我发现如果一个元素用单个 <g>
包裹标记它有动画延迟,但如果没有 <g>
或两个,不会发生延迟。
Firefox 对两个图像进行动画处理,没有动画延迟。
目前我已经手动取消了元素分组,但显然这不是一个好的解决方案,所以问题是如何在不更改文件的情况下解决它?
最佳答案
一个非常狡猾的错误,但很容易解决:只需将子选择器限制为非 g
元素即可:
svg {
width: 200px;
margin: 50px;
}
svg :not(g) {
transition: fill 1s;
}
svg:not(:hover) * {
fill: gray !important;
}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 3 1">
<rect x="0" y="0" width="1" height="1" style="fill: red" />
<rect x="1" y="0" width="1" height="1" style="fill: green" />
<rect x="2" y="0" width="1" height="1" style="fill: blue" />
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 3 1">
<g>
<rect x="0" y="0" width="1" height="1" style="fill: red" />
<rect x="1" y="0" width="1" height="1" style="fill: green" />
<rect x="2" y="0" width="1" height="1" style="fill: blue" />
</g>
</svg>
关于css - Chrome 上 <g> 标签内的 SVG 元素 CSS 过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55286289/