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

相关推荐
这个一个非常哈10 分钟前
element之,自定义form的label
前端·javascript·vue.js
阿东在coding25 分钟前
Flutter 测试框架对比指南
前端
是李嘉图呀29 分钟前
npm推送包失败需要Two-factor权限认证问题解决
前端
自己记录_理解更深刻30 分钟前
本地完成「新建 GitHub 仓库 react-ts-demo → 关联本地 React+TS 项目 → 提交初始代码」的完整操作流程
前端
借个火er31 分钟前
Chrome 插件开发实战:5 分钟上手 + 原理深度解析
前端
攀登的牵牛花32 分钟前
前端向架构突围系列 - 架构方法(一):概述 4+1 视图模型
前端·设计模式·架构
Hashan32 分钟前
Vue 3 中 v-for 动态组件 ref 收集失败问题排查与解决
前端·vue.js·前端框架
bobringtheboys34 分钟前
[el-tag]使用多个el-tag,自动判断内容是否超出
前端·javascript·vue.js
ccccc__34 分钟前
基于vue3完成领域模型架构建设
前端
Cherry的跨界思维36 分钟前
【AI测试全栈:Vue核心】19、Vue3+ECharts实战:构建AI测试可视化仪表盘全攻略
前端·人工智能·python·echarts·vue3·ai全栈·ai测试全栈