美文网首页【技术】前端小问题集锦
iconfont SVG 使用 & SVG 动态换颜色

iconfont SVG 使用 & SVG 动态换颜色

作者: 爱吐槽的小姐 | 来源:发表于2021-08-13 18:35 被阅读0次

    ### SVG 使用流程

    1. 首先在iconfont中加入待使用的图标

    2. 将生成的对应Symbol代码复制到lib/script/iconfont.js中

    3. 在页面中进行使用,例子

    ```

        <svg class="icon-svg nb-index__features-img" aria-hidden="true">

            <use class="nb-index__features-img-use"  xlink:href="#iconjulebu"></use>

        </svg>

    ```

    ### 备注:使用图标根据图标涉及的颜色多少,确定颜色修改方案。

    1.对于双色图标(不管有几条path,只有两种颜色的都算)多采用,删除其中一种颜色path的fill属性,然后设置另外一种颜色path的fill="currentColor",

    ```

    举例:

        配置

        <symbol id="iconshangcheng" viewBox="0 0 1046 1024">

            <path d="M1038.758731 ..." fill="currentColor" ></path>

            <path d="M700.883326 ..."></path>

            <path d="M763.948356 ...></path>

            <path d="M352.790184 ..." fill="currentColor" ></path>

        </symbol>

        使用

        <svg class="icon-svg nb-index__features-img" aria-hidden="true">

            <use class="nb-index__features-img-use"  xlink:href="#iconjulebu"></use>

        </svg>

        css

        .nb-index__features-img-us {

            fill: #554321; // 未配置fill的path颜色

            color: #99870; // currentColor的颜色

        }

    ```

    2.对于多色图标,使用css变量进行颜色处理

    ```

    举例三色图标:

        配置

        <symbol id="iconshangcheng" viewBox="0 0 1046 1024">

            <path d="M1038.758731 ..." fill="#333333" style="fill: var(--primary-color)"></path>

            <path d="M700.883326 ..." fill="#666666 style="fill: var(--secondary-color)"></path>

            <path d="M352.790184 ..." fill="#999999 style="fill: var(--tertiary-color)" ></path>

        </symbol>

        使用

        <svg class="icon-svg nb-index__features-img" aria-hidden="true">

            <use class="nb-index__features-img-use"  xlink:href="#iconjulebu"></use>

        </svg>

        css

        .nb-index__features-img-use {

            --primary-color: red; // path1 的颜色

            --secondary-color: pink;

            --tertiary-color: green;

        }

    ```

    3.直接在项目中修改iconfont.js文件本身

    如果是不同的项目使用了同一个svg图标,完全可以考虑在iconfont文件中批量处理svg的颜色。这样也能达到多个项目,颜色各不相同的效果,而且不需要在引用时再处理颜色。

    此种方式同样适用于saas类项目,根据当前项目配置的主题色,动态处理iconfont文件。

    参考链接:用CSS给SVG 的内容添加样式_SVG 教程_W3cplus

    相关文章

      网友评论

        本文标题:iconfont SVG 使用 & SVG 动态换颜色

        本文链接:https://www.haomeiwen.com/subject/msrjbltx.html