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

如何用JSON文件替换JavaScript变量实现轮播文本效果

实现Minecraft风格轮播文本并改用JSON存储内容

步骤1:创建JSON文本文件

新建一个名为splash-texts.json的文件,将轮播文本存为数组格式,放在和网页文件同一目录下:

[
    "world",
    "web",
    "video",
    "community",
    "service",
    "home",
    "place",
    "legacy",
    "space",
    "server"
]

步骤2:修改JS代码加载JSON数据

替换原硬编码数组,用fetch API加载JSON文件,加载完成后启动轮播逻辑:

let landingswitchtext = [];

// 加载JSON文本列表
fetch('splash-texts.json')
  .then(res => res.json())
  .then(data => {
    landingswitchtext = data;
    textSequence(0);
  })
  .catch(err => {
    console.error('加载文本列表失败:', err);
    // 加载失败时用兜底文本
    landingswitchtext = ['default'];
    textSequence(0);
  });

function textSequence(i) {
  if (landingswitchtext.length > i) {
    setTimeout(() => {
      // 用textContent替代innerHTML更安全,避免XSS风险
      document.getElementById("landing-text-switch").textContent = landingswitchtext[i];
      textSequence(++i);
    }, 2500);
  } else if (landingswitchtext.length === i) {
    // 循环轮播
    textSequence(0);
  }
}

步骤3:HTML部分保持不变

原有HTML代码无需修改,确保landing-text-switch这个ID的元素存在即可:

<div class="landing-page">
    <h1 class="landing-text">
        <center>
            building a
            <br>
            <br>
            <span class="magic" id="landing-text-switch">sam</span>
            <br>
            <br>
            for everyone.
        </center>
    </h1>
</div>

额外提示

  • 注意JSON文件路径:如果文件不在网页同级目录,要在fetch中填写正确的相对路径(比如./assets/splash-texts.json)
  • 若需要自定义每个文本的切换时长,可将JSON改成对象数组格式,示例:
    [
        {"text": "world", "delay": 2000},
        {"text": "web", "delay": 3000}
    ]
    
    之后在轮播函数中读取landingswitchtext[i].delay作为setTimeout的时长即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:40:47