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

如何修改CSS变量实现标题每秒切换字体?

解决方法

先纠正你CSS里的小问题:CSS变量中的字体名不需要加引号,把:root里的--red: "verdana";改成--red: verdana;,不然字体可能无法正常生效。

要实现每秒切换字体,核心是用JavaScript动态修改CSS变量,具体步骤和代码如下:

完整代码示例

HTML
<h1 style="text-align: center;">Fortune cookie!</h1>
<p style="text-align: center;">Check your luck by clicking the cookie!</p>
CSS
:root {
  --font-primary: verdana;
}
h1,p {
  font-family: var(--font-primary);
}

(把变量名改成--font-primary更语义化,你也可以继续用--red,只是名字更直观)

JavaScript
const root = document.querySelector(":root");
// 自定义要切换的字体列表,可自行添加更多字体
const fontList = ["verdana", "arial", "georgia", "courier new", "impact"];
let currentIndex = 0;

// 每秒执行一次字体切换逻辑
setInterval(() => {
  // 循环切换字体,到列表末尾自动回到开头
  currentIndex = (currentIndex + 1) % fontList.length;
  // 修改CSS变量的值
  root.style.setProperty('--font-primary', fontList[currentIndex]);
}, 1000);

关键说明

  • setInterval的第二个参数设为1000,代表每1000毫秒(1秒)执行一次回调函数
  • (currentIndex + 1) % fontList.length确保索引在字体列表范围内循环,不会出现越界问题
  • root.style.setProperty是修改CSS变量的正确方式,和你之前用getComputedStyle读取变量的操作对应,一存一取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:55:16