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

如何用JavaScript实现倒计时结束触发的爆炸GIF覆盖层可调用函数

实现倒计时结束时显示爆炸GIF的方案

首先修正你原代码里的一个问题:setInterval在倒计时结束后不会自动停止,会持续占用资源,所以需要先清除定时器。以下是完整的实现方案:

完整代码实现

window.onload = function () {
    var time = 299, // 倒计时总秒数
        display = document.querySelector('#timer');
    startTimer(time, display);
};

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    // 保存定时器ID,用于倒计时结束后终止定时器
    const timerInterval = setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            // 停止定时器
            clearInterval(timerInterval);
            // 调用显示爆炸GIF的函数
            showExplosionGif();
        }
    }, 1000);
}

// 显示爆炸GIF的核心函数
function showExplosionGif() {
    // 创建图片元素
    const explosionImg = document.createElement('img');
    // 替换为你实际的爆炸GIF路径(本地文件或线上地址都可以)
    explosionImg.src = 'explosion.gif';
    // 设置样式让GIF全屏覆盖页面
    explosionImg.style.position = 'fixed';
    explosionImg.style.top = '0';
    explosionImg.style.left = '0';
    explosionImg.style.width = '100vw';
    explosionImg.style.height = '100vh';
    explosionImg.style.objectFit = 'cover';
    explosionImg.style.zIndex = '9999'; // 确保GIF在所有页面元素上方
    explosionImg.style.pointerEvents = 'none'; // 不干扰页面其他操作(可选)
    
    // 将GIF添加到页面中
    document.body.appendChild(explosionImg);

    // 可选:GIF播放完成后自动移除,这里设为2秒(可根据你GIF的时长调整)
    setTimeout(() => {
        document.body.removeChild(explosionImg);
    }, 2000);
}

关键细节说明

  • 终止定时器:用clearInterval清除定时器,避免倒计时结束后代码仍在后台执行。
  • 全屏覆盖样式:通过fixed定位让GIF铺满整个屏幕,z-index设置为高数值保证它显示在所有内容上方,objectFit: cover确保GIF不会变形。
  • 自定义扩展:如果需要让用户手动关闭GIF,可以添加点击事件:
    explosionImg.style.pointerEvents = 'auto'; // 开启点击交互
    explosionImg.addEventListener('click', () => {
        document.body.removeChild(explosionImg);
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 22:17:08