Lit开发:字体图标的使用

遇到的问题

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

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

我的解决思路

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

第一步:引入字体定义

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

css 复制代码
@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创建一个图标组件,代码如下:

ts 复制代码
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中定义的样式,内容如下:

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文件后,即可使用图标组件,下面是使用的一个例子:

html 复制代码
<ant-icon class="icon-loading" color="white" />

总结

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

相关推荐
粥里有勺糖21 分钟前
视野修炼-技术周刊第130期 | 光影效果
前端·javascript·github
小岛前端35 分钟前
AI Skills 已经封神,但新的问题却越来越严重!
前端·后端·github
拖孩39 分钟前
一个人 + AI 做的小程序,上线 15 天赚了 10 块 5
前端·后端·微信小程序
用户939838294159940 分钟前
安卓自动化脚本热更新怎么做?不重新打包 APK 也能更新代码
前端
猫七先生1 小时前
在 React 里用 PMTiles 自托管底图
前端
tanghonghanhaoli1 小时前
【图书翻译】有意义的游戏设计:桌面游戏的方法论与心理学(第1、2章)
前端·游戏·ui
光影少年1 小时前
react native打包优化、包体积瘦身、离线包/热更新方案
前端·react native·react.js
Cache技术分享1 小时前
504. Java 反射 - 创建一个简单的依赖注入框架
前端·后端
_codeOH1 小时前
# 手把手复刻 DeepSeek 官网效果:玻璃拟态 + WebGL 流体 + Spring 动画,一篇讲透
前端
名字还没想好☜1 小时前
Next.js 用 cookies()/headers() 读请求信息:动态渲染触发、缓存失效与在 Server Action 里读写 cookie
前端·javascript·缓存·react·next.js·app router