iconfont 字体图标 angular 封装引用 font-class引用和symbol引用

hello,大家好,欢迎来到Altaba的博客
先来讲解 symbol引用
最新项目中,要用到彩色字体图标 做表情,故在项目中使用了阿里巴巴的iconfont 按照官网的使用方式如下:
在这里插入图片描述
angular中顺序是:
第一步:建议使用本地symbol代码
(1)下载好iconfont网站的图标,解压,将iconfont.js 放到 assets目录下,可以自己建一个font文件夹存放这个文件;
(2)然后在 angular.json 文件的projects -> architect -> build -> options -> scripts 数组中引入这个文件,例如:“src/assets/font/iconfont.js”。
第二步:
加入通用css代码
可以在最外面的style.scss(某些项目是style.css或者style.less)中加入如下代码,为了初始化图标样式

.icon {
  width: 1em; height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

第三步:封装成angular组件
代码如下:

html

<svg class="icon" aria-hidden="true">
  <use [attr.xlink:href]="type"></use>
</svg>

ts

import {
    Component, Input, OnInit
} from '@angular/core';

@Component({
  selector: 'icon-font',
  templateUrl: './icon.component.html',
  styleUrls: ['./icon.component.scss']
})
export class IconComponent implements OnInit {

  constructor(
    ) { }
  @Input() type: string;
  ngOnInit() {
    this.type = '#' + this.type;
  }
}

完成!方式及其简单,需要注意的是 html中 use标签的 xlink:href 属性绑定变量通过 [attr.xlink:href]="type"绑定!!!
这是最简版本,可以自行添加配置自定义样式等
特点如下

  1. 支持多色图标了,不再受单色限制
  2. 通过一些技巧,支持像字体那样,通过font-size,color来调整样式。
  3. 兼容性较差,支持 ie9+,及现代浏览器。
  4. 浏览器渲染svg的性能一般,还不如png。

font-class引用方式:
该方式比较常见,使用如下:
步骤1: iconfont 官网下载好打包的字体图标,解压,将文件 iconfont.css,iconfont.eot,iconfont.svg,iconfont.ttf,iconfont.woff放在assets的font文件夹下,如果没有font文件夹自行创建下
步骤2:
然后在 angular.json 文件的projects -> architect -> build -> options -> styles 数组中引入这个文件,例如:“src/assets/font/iconfont.css”。
步骤3
这样你就可以在页面上,使用图标了,例如:

<i calss="iconfont icon-xxx"></i>

如有不了解,请留言,看见必回复。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值