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

求助:实现h1打字机效果时报错Cannot read properties of undefined

问题原因

错误Cannot read properties of undefined (reading 'substring')是因为后续调用typewriter时没有传入文本参数:

  • 第一次调用typewriter('Test')时,message是正常字符串;
  • 但setTimeout(typewriter, speed)没有传递参数,导致下一次执行typewriter时,event(即message)为undefined,调用substring就会触发报错。
修复方案

这里提供两种可行的修复方式:

方案1:利用闭包保存文本(推荐)

把文本变量放在外层函数中,内部写逻辑的函数可直接访问,避免参数传递问题:

const speed = 50;

function typewriter(message) {
    let textPosition = 0;
    
    function write() {
        // 替换#message为你的h1标签ID
        document.querySelector("#message").innerHTML = message.substring(0, textPosition) + '<span>\u2758</span>';
        
        if (textPosition++ !== message.length) {
            setTimeout(write, speed);
        }
    }
    
    write();
}

window.onload = function() {
    typewriter(`Test`);
};

方案2:用全局变量保存当前文本

通过全局变量存储要打印的文本,初始化时赋值,后续调用无需传参:

const speed = 50;
let textPosition = 0;
let currentMessage = '';

function typewriter(message) {
    // 首次调用时初始化文本和位置
    if (message) {
        currentMessage = message;
        textPosition = 0;
    }
    
    document.querySelector("#message").innerHTML = currentMessage.substring(0, textPosition) + '<span>\u2758</span>';
    
    if (textPosition++ !== currentMessage.length) {
        setTimeout(typewriter, speed);
    }
}

window.onload = function() {
    typewriter(`Test`);
};
注意事项

确保你的HTML中有对应的h1标签:

<h1 id="message"></h1>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:17:16