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

相关推荐
计算机魔术师7 分钟前
出题人自己算错了,AI成绩从88%直接跳到98%
前端
Amos_Web25 分钟前
Rspack 源码解析(三十一):HotModuleReplacementPlugin 如何用 hash 比对生成增量更新
前端
尤水就下36 分钟前
🔥说一说在线文档的 Block 架构是如何实现的
前端·javascript·架构
是江迪呀1 小时前
介绍一个开源项目 —— 烂笔头
前端·后端
恋猫de小郭1 小时前
Flutter 紧急发布 3.47.8 安全升级版本,建议都升级
android·前端·flutter
紧跟先前的步伐1 小时前
Go AI Agent 实战 18|Tool Calling 的基本原理与完整执行流程
前端·数据库·人工智能·ai·golang·1024程序员节
captain3761 小时前
Spring Web MVC(2)
java·前端·spring boot·后端·spring·mvc
晓得迷路了1 小时前
栗子前端技术周刊第 151 期 - ViteConf 2026、React Router 8.5、React Native 0.88...
前端·javascript·vue.js
ai工具集合1 小时前
老项目位图图标放大模糊?PNG 一键转 SVG 矢量化实操,附前端避坑指南
前端
2601_968708031 小时前
DreamsChat Web – Chat, Audio, Video Web APP with Admin Dashboard
前端·架构