Chrome 上的 <g> 标签内的 SVG 元素 CSS 过渡

SVG elements CSS transition inside <g> tag on Chrome

所以我创建了一个页面,其中包含一些彩色 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>