SVG图标颜色跟随文字颜色变化的简单实现

不要再写条件判断更换SVG图标了,一行CSS搞定

0.前言

项目中经常会遇到这样一个小需求:某个按钮hover的时候按钮字体要变色,同时按钮图标也要变色。这个时候如果写JS条件判断那就恶心死了,有没有比较简单的办法呢?

1.准备demo

这里我随便找了个图标,用div做了一个按钮,比较粗糙但是不影响效果:

<h1>假装他是一个按钮</h1>
<div class="box">
    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
        <path fill-rule="evenodd" clip-rule="evenodd"
            d="M5 3C3.89543 3 3 3.89543 3 5V15C3 16.1046 3.89543 17 5 17H15C16.1046 17 17 16.1046 17 15V5C17 3.89543 16.1046 3 15 3H5ZM12.4281 8.75417C12.4546 8.74866 12.4816 8.74588 12.5086 8.74585C13.2206 8.76763 13.7861 9.3701 13.7835 10.1041C13.786 10.8378 13.221 11.44 12.5094 11.4622C12.49 11.4616 12.4708 11.4597 12.4517 11.4564C12.2345 12.3303 11.4726 12.9433 10.5972 12.9485C10.4688 13.1669 10.2392 13.3004 9.99138 13.3008C9.59795 13.3008 9.27901 12.9721 9.27901 12.5667C9.27881 12.372 9.35372 12.1852 9.48726 12.0474C9.6208 11.9096 9.80202 11.8321 9.991 11.8321C10.2079 11.8327 10.4126 11.9357 10.5465 12.1115C10.8455 12.1249 11.1369 12.0122 11.3535 11.7994C11.5702 11.5865 11.6932 11.2919 11.6944 10.9834V9.39401C11.6933 8.4251 10.9313 7.63994 9.991 7.63874C9.05006 7.64016 8.28804 8.42661 8.28815 9.39619L8.2916 10.9043C8.29196 11.0523 8.23522 11.1945 8.13386 11.2995C8.0325 11.4044 7.89483 11.4636 7.75113 11.464H7.47878V11.462H7.47437C6.76267 11.4399 6.19759 10.8376 6.2002 10.1039C6.19759 9.37023 6.76267 8.76794 7.47437 8.74585C7.50145 8.74588 7.52848 8.74866 7.55503 8.75417C7.83964 7.60659 8.84192 6.803 9.99138 6.80078C11.141 6.80282 12.1435 7.60645 12.4281 8.75417Z"
            fill="#777C99" />
    </svg>
    <span class="text">客服</span>
</div>
.box {
    display: flex;
    align-items: center;
    width: fit-content;
    padding: 5px 10px;
    border-radius: 4px;
    border: 1px solid black;
    cursor: pointer;
    background-color: #fff;
}

.box:hover {
    background-color: #466AFF;
    color: white;
}

可以看到图标并没有跟着字体一起变成白色:

2.SVG中fill属性

SVG图标各个部分的颜色是由属性fill控制的:

<!-- svg中fill表示整体的填充色,path中fill表示这部分的填充色,当前的填充色为#777C99 -->
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
    <path fill-rule="evenodd" clip-rule="evenodd"
        d="...省略"
        fill="#777C99" />
</svg>

让我们随便改一个颜色看一下效果:

<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="red">
    <path fill-rule="evenodd" clip-rule="evenodd"
        d="...省略"
        fill="red" />
</svg>

3.使用currentColor关键字

fill="currentColor"是一个非常实用的技巧:

  • 让SVG图标自动继承父元素的文字颜色
  • 减少了维护成本,只需要修改一处color属性
  • 特别适合hover、active等状态下的颜色联动

kucha
“ 大冬天的非常冷,打工人很辛苦,需要一杯奶茶暖暖肚子。 ”
 喜欢文章
1人喜欢
头像