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

相关推荐
营赢盈英1 小时前
How to detect if <html> tag has a class in child Angular component
前端·javascript·css·html·angular.js
Achieve - 前端实验室1 小时前
深入浅出 ES Module
前端·javascript
littleplayer1 小时前
Combine 基本使用指南
前端
Lethehong2 小时前
TRAE SOLO:基于React 18+与蓝耘MaaS的多语言智能翻译平台设计与实现
前端·react.js·前端框架·蓝耘元生代·蓝耘maas
技算未来2 小时前
Electron中使用exceljs+Node模块编写
前端
Qinana2 小时前
🚀 用低代码构建AI职业规划应用
前端·程序员·产品
Ebin2 小时前
Shopify 前端实战系列 · S02:Theme 实战进阶
前端
青衫码上行2 小时前
【JavaWeb学习 | 第二篇】CSS(1) - 基础语法与核心概念
前端·css·学习
残冬醉离殇2 小时前
🔥 什么?不用鼠标点击也能触发点击事件???前端工程师的认知塌了!
前端·javascript