vue项目使用自定义字体,不同浏览器环境使用不同字体

使用本地字体文件

1、在 scr/assets 目录下创建一个名为 fonts的文件夹。将字体文件(通常是 .ttf 或 .woff 格式)复制到文件夹中

2、在 scr/styles 目录下创建font.scss/less/css 文件。在文件中,使用 @font-face 规则来定义自定义字体    

@font-face {
    font-family: 'pingfangsc-regular';
    src: url('../assets/custom-theme/fonts/pingfangsc-regular.otf') format('opentype');
}

@font-face {
    font-family: 'pingfangsc';
    src: url('../assets/custom-theme/fonts/pingfangsc.ttf') format('opentype');
}


@font-face {
  font-family: 'YourFontName';
  src: url('./your-font-file.ttf') format('truetype');
  /* 可以添加其他字体格式的来源,例如: */
  /* src: url('./your-font-file.woff') format('woff');  */
  /* src: url('./your-font-file.eot') format('embedded-opentype');  */
}

/* 可以定义其他样式属性,例如: */
/* .custom-font-class { */
/*   font-family: 'YourFontName', sans-serif; */
/* } */

 3、在入口文件main.js中引入

import './styles/font.scss'

4、在 Vue 项目中使用该自定义字体

 .btm-number {
     font-family: "D-DIN";
     color: #EC0000;
 }

使用后端提供的线上字体地址

本地字体文件一般都是几十M上百M,会让项目打包文件变得很大,建议让后端把字体文件放在服务器,使用线上字体。

使用方法跟本地字体的类似,不需要第一步

使用 @font-face 规则来定义自定义字体时注意引入地址

@font-face {
    font-family: "D-DIN";
    src: url('https://test.com/api/admin/static/font/D-DIN-PRO-500-Medium.ttf');
}

不同浏览器环境使用不同字体

如果设计要求只能在苹果电脑上显示苹果字体,window电脑显示微软雅黑字体,可以在入口文件判断当前浏览器环境,再使用对应字体。

//main.js

const userAgent = window.navigator.userAgent.toLowerCase();

const regex = /windows/;
if (regex.test(userAgent)) {
  // windows系统
  document.documentElement.style.fontFamily = '"Microsoft YaHei", "微软雅黑", "Helvetica Neue", Helvetica, "Hiragino Sans GB", Arial, sans-serif';
} else {
  // 苹果系统
  document.documentElement.style.fontFamily = '-apple-system, pingfangsc-regular, pingfangsc-medium, "Microsoft YaHei", "微软雅黑","Helvetica Neue", Helvetica, "Hiragino Sans GB", Arial, sans-serif';
}
console.log('window系统', regex.test(userAgent));
console.log('浏览器环境', userAgent, typeof userAgent);

window系统的输出参数: 

正则表达式不能用‘apple’判断浏览器环境,因为window系统参数也会出现‘apple’字段。

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值