[英]Toggle color of SVG icons
I want the fill color of this SVG icon to change once I click on it and change back when I click on it again.我希望这个 SVG 图标的填充颜色在我点击它时改变,并在我再次点击它时改变回来。 How do I do this?
我该怎么做呢? I preferably want to do this using Javascript.
我最好使用 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>
I modified your CSS codes by only adding "clicked" class and I also wrote a simple JS script.我修改了你的 CSS 代码,只添加了“clicked”类,我还写了一个简单的 JS 脚本。 Here is how you can do this by 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.