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

标签 css google-chrome svg transition fill

所以我创建了一个包含一些彩色 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/

相关文章:

css - 嵌套的 div 和 CSS 语义

CSS关键帧动画-webkit-transform重置Chrome Bug

google-chrome - 在 Google Chrome 扩展程序中识别机器/用户的最佳方法是什么?

css - 不同 svg-filters 之间的过渡 - 如何?

jquery - 如何在 CSS 或 jquery 中的三 Angular 形图像上制作剪贴蒙版?

html - 如何避免 Safari 将 -apple-system-blue 添加到我的按钮

javascript - 使用 jQuery 更改光标的 CSS

javascript - Google Web 字体在 OSX Safari 中不显示,但在 Firefox、Chrome、Opera(适用于 OSX、Windows 和 Linux)和 Internet Explorer 中显示

html - Chrome的HTML5语音识别API实现中的语言代码是什么?

javascript - 画一条连接数据点的线