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

如何在点击动画触发后添加延迟,使h1元素2秒后恢复为50px字体大小

实现方案

使用浏览器内置的setTimeout定时器API即可实现延迟恢复的需求,修改后的代码如下:

const h1 = document.querySelector('.hi');

h1.addEventListener('click', ()=>{
    h1.style.fontSize = '90px';
    // 2000毫秒对应2秒,延迟到期后执行回调内的恢复逻辑
    setTimeout(() => {
        h1.style.fontSize = '50px';
    }, 2000);
});

如果需要处理用户多次连续点击的场景,避免定时器叠加导致效果异常,可以新增状态锁做判断:

const h1 = document.querySelector('.hi');
// 状态锁,标记当前是否在切换周期内
let isSwitching = false;

h1.addEventListener('click', ()=>{
    if (isSwitching) return;
    isSwitching = true;
    h1.style.fontSize = '90px';
    setTimeout(() => {
        h1.style.fontSize = '50px';
        isSwitching = false;
    }, 2000);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:42:03