为什么 CSS 过滤器不适用于 Chrome 中的 SVG 元素? [英] Why don't CSS filters work on SVG elements in Chrome?

查看:18
本文介绍了为什么 CSS 过滤器不适用于 Chrome 中的 SVG 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,CSS 过滤器应该在 Chrome 的任何地方工作,但我没有它们适用于 SVG 元素.

As far as I understand, CSS filters should work anywhere in Chrome, but I fail to make them apply to SVG elements.

这适用于所有大多数浏览器:

This works fine in all most browsers:

div{ filter:sepia(50%) }

但是,这在 Chrome 中不起作用:

However, this will not work in Chrome:

rect{ filter:sepia(50%) }

这是一个例子:

div{
    width:100px;
    height:50px;
    background-color:red;
}
rect{
    fill:red;
}
rect:hover, div:hover{
    -webkit-filter:sepia(50%);
    -moz-filter:sepia(50%);
    filter:sepia(50%);
}

<h2>SVG</h2>
<svg width="100" height="50">
    <rect x="0" y="0" width="100" height="50"/>
</svg>


<h2>DIV</h2>
<div></div> 

...这里是一个小提琴:https://jsfiddle.net/LtffLagn/2/

...and here is a fiddle: https://jsfiddle.net/LtffLagn/2/

推荐答案

感谢 @Robert Longson,谁给出了答案:CSS 过滤器不能应用于 Chrome 中的 SVG 元素.但是,它们可以重新实现为 SVG 过滤器,但需要做一些额外的工作.这就是我最终的结果:

All credit to @Robert Longson, who gave the answer: CSS filters can not be applied to SVG elements in Chrome. They can, however, be re-implemented as SVG filters, with some extra work. This is what I ended up with:

rect{
  fill:red;
}
rect:hover{
    filter:url("#sepia");
    filter:sepia(100%);
}

    <svg width="100" height="50">
      <defs>
        <filter id="sepia">
          <feColorMatrix type='matrix' values='0.30 0.30 0.30 0.0 0
                                               0.25 0.25 0.25 0.0 0
                                               0.20 0.20 0.20 0.0 0
                                               0.00 0.00 0.00 1 0'/>
        </filter>
      </defs>
      <rect x="0" y="0" width="100" height="50"/>
    </svg>

Firefox 现在将使用 CSS 过滤器,Chrome 将使用 SVG 过滤器.当然,如果您设法使 SVG 过滤器按照您想要的方式工作,您就可以坚持下去.对我来说,我从来没有设法得到我想要的效果,所以我让 Firefox 使用更好看的 CSS 过滤器.

Firefox will now use the CSS filter, and Chrome the SVG filter. Of course, if you manage to make the SVG filter work the way you want, you could just stick with that. For me, I never managed to get exactly the effect I wanted, so I let Firefox use the better looking CSS filter.

Chrome/ium 中 SVG 元素上 CSS 过滤器的错误跟踪器:https://bugs.chromium.org/p/chromium/issues/detail?id=109224

Bug tracker for CSS filters on SVG elements in Chrome/ium: https://bugs.chromium.org/p/chromium/issues/detail?id=109224

编辑 2021 年 2 月:SVG 元素上的 CSS 过滤器将开始工作Chrome 89,如果一切按计划进行!

Edit February 2021: CSS filters on SVG elements will start working in Chrome 89, if everything goes according to plan!

这篇关于为什么 CSS 过滤器不适用于 Chrome 中的 SVG 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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