如何获得可在嵌套SVG上使用的过滤器?

时间:2019-07-17 18:26:20

标签: css svg

我正在尝试为某些svg提供悬停效果。我正在处理的代码基本上是svg中包含的图标,因此它们都位于背景顶部(看起来像地图-我希望地图上的各个图标在悬停时突出显示)。

问题是过滤器似乎对嵌套的svg元素没有任何影响。我试过将过滤器直接放在嵌套元素中,它不会改变任何内容。

这是我想工作的简单代码示例。

.icon:hover{
        filter: sepia(100%);
      }
<html>
  <body>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

      <svg x="10" class="icon">
        <rect x="10" y="10" height="100" width="100" style="fill: #0000ff"/>
      </svg>
      <svg x="200">
        <rect x="10" y="10" height="100" width="100" style="fill: #0000ff"/>
      </svg>

    </svg>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以使用svg过滤器。 sepiatone过滤器来自https://gist.github.com/jorgeatgu/5b338cc1a4e0df901348

svg{border:1px solid}

.icon:hover{
    filter: url(#sepiatone);
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<filter id="sepiatone">
  <feColorMatrix type="matrix" values=".343 .669 .119 0 0 .249 .626 .130 0 0 .172 .334 .111 0 0 .000 .000 .000 1 0"/>
</filter>
</defs>
      <svg x="10" class="icon">
        <rect x="10" y="10" height="100" width="100" style="fill: #0000ff"/>
      </svg>
      <svg x="200">
        <rect x="10" y="10" height="100" width="100" style="fill: #0000ff"/>
      </svg>
    </svg>