[英]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>
懸停不夠具體。
#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.