You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在@font-face规则中引入替代字符字体并实现随机调用

Manic字体引入及随机字符调用实现方案

1. 用@font-face引入四个字体文件

先给四个字体分别定义独立的font-family标识,注意替换url路径为你服务器上的字体实际存放地址:

/* 常规版本字体 */
@font-face {
  font-family: 'Manic Regular';
  src: url('./fonts/manic-regular.woff') format('woff');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}
/* 替代字符版本1 */
@font-face {
  font-family: 'Manic Alt 1';
  src: url('./fonts/manic-alt-1.woff') format('woff');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}
/* 替代字符版本2 */
@font-face {
  font-family: 'Manic Alt 2';
  src: url('./fonts/manic-alt-2.woff') format('woff');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}
/* 替代字符版本3 */
@font-face {
  font-family: 'Manic Alt 3';
  src: url('./fonts/manic-alt-3.woff') format('woff');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

2. 实现字符随机调用

提供两种实现方案,可根据兼容性需求选择:

方案A:纯CSS实现(适合现代浏览器)

利用CSS原生random()函数直接给每个字符随机分配字体,不需要写JS代码:

/* 给需要应用效果的文本添加类名manic-random */
.manic-random {
  --font-list: 'Manic Regular', 'Manic Alt 1', 'Manic Alt 2', 'Manic Alt 3';
}
.manic-random > * {
  font-family: var(--font-list, random(4));
}

方案B:JS+CSS实现(全浏览器兼容)

兼容性覆盖所有主流浏览器,稳定性更高:

第一步:添加基础样式

.manic-random span {
  display: inline-block;
  line-height: 1.2; /* 统一行高避免排版错位 */
}
.font-0 { font-family: 'Manic Regular'; }
.font-1 { font-family: 'Manic Alt 1'; }
.font-2 { font-family: 'Manic Alt 2'; }
.font-3 { font-family: 'Manic Alt 3'; }

第二步:添加JS逻辑

const randomManicFont = () => {
  const textEls = document.querySelectorAll('.manic-random');
  textEls.forEach(el => {
    const charList = el.textContent.split('');
    el.innerHTML = '';
    charList.forEach(char => {
      const span = document.createElement('span');
      span.textContent = char;
      const randomIndex = Math.floor(Math.random() * 4);
      span.classList.add(`font-${randomIndex}`);
      el.appendChild(span);
    });
  });
}
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', randomManicFont);

注意事项

  • 若需要固定某些字符的字体样式,可在JS逻辑中添加判断规则,单独给指定字符分配固定类名即可
  • 所有字体文件的CORS配置要正确,避免跨域问题导致字体加载失败

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 12:27:05