使用本地字体文件
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’字段。