悬停时更改 SVG 多边形的颜色

3
我想使用 CSS 在鼠标悬停时更改 SVG 的每个多边形的颜色。
以下是 HTML 代码:
<svg class="compass-svg" width="200" height="200">
     <polygon id="N" points="100,10 125,50 100,100 75,50" style="fill:#fff; stroke:#000; stroke-width: 1;"/>
     <polygon id="NE" points="155,45 150,75 100,100 125,50" style="fill:#fff; stroke:#000; stroke-width: 1;"/>
</svg>

当我悬停在多边形之一上时,它的填充颜色应更改为#000。
我已经尝试使用ID更改颜色:
/*This does not work*/
#N:hover {
    fill: #000;
}

我发现这个解决方案使用了jquery,但我想知道是否可以通过纯CSS实现: 我的SVG多边形的填充在悬停时不会改变颜色

4个回答

3

是的,因为你在 SVG 中使用了内联样式。 你可以保留它并在 CSS 中添加 !important 来覆盖其他样式。

#N {
fill: #000 !important;
}

或者执行以下操作

#N{fill: #000;}
<svg class="compass-svg" width="200" height="200">
     <polygon fill="#fff" stroke="#000" stroke-width="1" id="N" points="100,10 125,50 100,100 75,50"/>
     <polygon fill="#fff" stroke="#000" stroke-width="1" id="NE" points="155,45 150,75 100,100 125,50"/>
</svg>

如果您希望在悬停时更改填充颜色,只需将:hover添加到#N

#N:hover {
fill: #000 !important;
}

或者

#N:hover{fill: #000;}
<svg class="compass-svg" width="200" height="200">
     <polygon fill="#fff" stroke="#000" stroke-width="1" id="N" points="100,10 125,50 100,100 75,50"/>
     <polygon fill="#fff" stroke="#000" stroke-width="1" id="NE" points="155,45 150,75 100,100 125,50"/>
</svg>


1
悬停效果不够明显。
  • 如果将元素的填充转换为CSS映射属性,它将起作用。
  • 或者,您可以在悬停填充上添加!important。

#N:hover {
    fill: red;
}
<svg class="compass-svg" width="200" height="200">
     <polygon id="N" points="100,10 125,50 100,100 75,50" fill="#fff" style="stroke:#000; stroke-width: 1;"/>
     <polygon id="NE" points="155,45 150,75 100,100 125,50" style="fill:#fff; stroke:#000; stroke-width: 1;"/>
</svg>


!important 起了作用。我只是忘记在问题中使用 :hover。 - Philip F.

1

我是如何找到解决方法的:

这是样式

#N:hover {
    fill: #000;
}

#NE:hover {
    fill: #000;
}

#NE {
 fill: #fff;
}
#N {
 fill: #fff;
}
<svg class="compass-svg" width="200" height="200">
     <polygon id="N" points="100,10 125,50 100,100 75,50" style="stroke:#000; stroke-width: 1;"/>
     <polygon id="NE" points="155,45 150,75 100,100 125,50" style="stroke:#000; stroke-width: 1;"/>
</svg>


0

当您使用内联样式时,需要使用 !important。

#N:hover,#NE:hover {
    fill: black!important;
}
<svg class="compass-svg" width="200" height="200">
     <polygon id="N" points="100,10 125,50 100,100 75,50" style="fill:#fff; stroke:#000; stroke-width: 1;"/>
     <polygon id="NE" points="155,45 150,75 100,100 125,50" style="fill:#fff; stroke:#000; stroke-width: 1;"/>
</svg>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接