簡體   English   中英

切換 SVG 圖標的顏色

[英]Toggle color of SVG icons

我希望這個 SVG 圖標的填充顏色在我點擊它時改變,並在我再次點擊它時改變回來。 我該怎么做呢? 我最好使用 Javascript 來做到這一點。

 .remove svg{ fill: gray; opacity: 0.8; height: 50px; width: 45px; } .remove svg:hover{ fill: red; opacity: 0.7; transition-duration: 0.3s; } button{ appearance: none; width: 47.5px; height: 50px; box-sizing: border-box; position: relative; background: white; border: none; cursor: pointer; }
 <button class="remove"> <svg version="1.1" id="Capa_1" id="removeB" class="removeB" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 328.51 328.51" style="enable-background:new 0 0 328.51 328.51;" xml:space="preserve"> <polygon points="229.044,88.858 164.255,153.647 99.466,88.858 88.858,99.466 153.647,164.255 88.858,229.044 99.466,239.651 164.255,174.862 229.044,239.651 239.651,229.044 174.862,164.255 239.651,99.466"/> </svg> </button>

我修改了你的 CSS 代碼,只添加了“clicked”類,我還寫了一個簡單的 JS 腳本。 以下是您可以通過 JS 執行此操作的方法:

.remove svg{
  fill: gray;
  opacity: 0.8;
  height: 50px;
  width: 45px;
}
.remove.clicked svg{
  fill: red;
  opacity: 0.7;
  transition-duration: 0.3s;
}
 button{
  appearance: none;
  width: 47.5px;
  height: 50px;
  box-sizing: border-box;
  position: relative;
  background: white;
  border: none;
  cursor: pointer;
}
var button = document.querySelector("button");

    button.addEventListener("click", function(){
        this.classList.toggle("clicked");
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM