如何在点击动画触发后添加延迟,使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
相关产品推荐
相关产品推荐

