内联SVG 删除先前:悬停填充

问题描述 投票:0回答:1

我想在悬停在其中一个父元素上时更改SVG的填充。最初我复制了元素中的完整svg:

<div class="topMenu__item">
    <div class="topMenu__item__icon">
        <svg>
            <g><path d="..." /></g>
        </svg>
    </div>
</div>

来自css的波纹管:hover工作得很好:

.topMenu__item:hover svg path {
    fill:yellow;
}

但为了更好的维护,我转而使用<use>并在html的末尾定义了svg。

<div class="topMenu__item">
    <div class="topMenu__item__icon">
        <svg>
            <use xlink:href="#home-icon"></use>
        </svg>
   </div>
</div>

定义如下所示:

<svg style:"display: none;">
    <defs><g id="home-icon"><path d="..." /></g></defs>
</svg>

这样做,:hover不再起作用了。为什么这样,我该如何纠正呢?

html css svg
1个回答
0
投票

我相信这就是你要找的:https://codepen.io/PhilC77/pen/drMgRY

<head>
<style type="text/css">
  .myIcon {
    display: inline-block;
    background-repeat: no-repeat;     
  }

  .testInner {
    fill: green;
  }

  .testInner:hover,
  .getGoogle:hover {
    fill: violet;
  }
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
  <defs>
    <symbol id="myicon-checkmark" viewBox="0 0 32 32">
      <title>checkmark</title>
      <path d="M 16 3 c -7.18 0 -13 5.82 -13 13 s 5.82 13 13 13 s 13 -5.82 13 -13 s -5.82 -13 -13 -13 Z M 23.258 12.307 l -9.486 9.485 c -0.238 0.237 -0.623 0.237 -0.861 0 l -0.191 -0.191 l -0.001 0.001 l -5.219 -5.256 c -0.238 -0.238 -0.238 -0.624 0 -0.862 l 1.294 -1.293 c 0.238 -0.238 0.624 -0.238 0.862 0 l 3.689 3.716 l 7.756 -7.756 c 0.238 -0.238 0.624 -0.238 0.862 0 l 1.294 1.294 c 0.239 0.237 0.239 0.623 0.001 0.862 Z" />
    </symbol>
  </defs>
</svg>

<h4 style="color: blue">Quick explanation of the hover fill concept. Of course you need to format the div ect.</h4>
<h3>Just Icon:</h3>
<div class="testInner">
  <svg class="myicon myicon-checkmark">
    <use xlink:href="#myicon-checkmark"></use>
  </svg>
</div>

<h3>Icon w/Redirect</h3>
  <a href="https://www.google.com/" title="Redirect to Google" target="_blank" class="getGoogle">
    <svg class="myicon myicon-checkmark">
      <use xlink:href="#myicon-checkmark"></use>
    </svg>
  </a>
</body>
© www.soinside.com 2019 - 2024. All rights reserved.