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

时间:2020-03-30 15:26:34

标签: html css svg polygon

我想使用CSS更改悬停时svg的每个多边形的颜色。

这是hmtl代码:

else

当我将一个多边形悬停时,其填充应变为#000。

我已经尝试使用ID更改颜色:

main

我找到了使用jquery的解决方案,但是我不知道是否可以使用纯CSS实现此解决方案: my svg polygons fills are not changing color on hover

4 个答案:

答案 0 :(得分:2)

是的,因为您的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;
}

OR

#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 :(得分: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>

答案 2 :(得分: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>

答案 3 :(得分: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>