繁体   English   中英

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

[英]Change color of svg polygon on hover

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

这是 hmtl 代码:

<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 多边形填充在悬停时不会改变颜色

是的,因为您的 svg 中有内联样式。 您可以保留它并将 !important 添加到您的 css 中

#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>

悬停不够具体。

  • 如果您将元素的填充转换为 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>

这是我想出的方法:

这是造型

 #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>

当您使用内联样式时,您需要使用 !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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM