Lit开发:字体图标的使用

123 阅读1分钟

遇到的问题

字体图标的使用方式有多种,这里以【font-class】方式来使用字体图标,首先引入css文件和字体文件,然后在元素【i或span】上设置相应类名来展示图标。

而Lit基于web components技术,其组件中的元素不能继承全局样式,所以全局的类名不生效,因此需要做一些变通。

我的解决思路

将字体图标的使用分为两步:

第一步:引入字体定义

在全局中定义字体,代码如下:

@font-face {
    font-family: 'iconfont';
    src:
        url('iconfont.woff2?t=1759101658372') format('woff2'),
        url('iconfont.woff?t=1759101658372') format('woff'),
        url('iconfont.ttf?t=1759101658372') format('truetype');
}

这是一个css文件的内容,可以在html文件中使用link标签引入该文件。

第二步:创建图标组件

使用Lit创建一个图标组件,代码如下:

import { html, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import style from './style';

@customElement('ant-icon')
export default class AntIcon extends LitElement {
    static styles = [style];

    @property({ type: String })
    size = '16px';

    @property({ type: String })
    color = '#333';
  
    @property({ type: String })
    icon = 'loading';

    render() {
        return html`
            <span class="iconfont icon-${this.icon}" style="font-size: ${this.size};color: ${this.color};"></span>
        `;
    }
}

其中引用了style.ts中定义的样式,内容如下:

import { css } from 'lit';

export default css`
.iconfont {
  font-family: 'iconfont' !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-loading:before {
  // 注意这里要多加一个\
  content: '\\e73c';
}
`;

稍微有一些麻烦的是,在【content】值中要多加一个【\】,然后就可以了。

第三步:使用图标

引入图标组件的ts文件后,即可使用图标组件,下面是使用的一个例子:

<ant-icon class="icon-loading" color="white" />

总结

在Lit中使用字体图标分为两步,第一步在全局引入字体定义与对应文件,第二步创建包含图标样式的图标组件。