You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

零基础开发者求助:如何用JS实现弹窗倒计时器及结束提示?

完全可行!这里有个零经验也能用的弹窗倒计时器

当然没问题!哪怕你几乎没碰过编程,也能轻松用上这个倒计时器——我特意写了一段超简单的代码,你只需要复制粘贴就能搞定。

怎么操作?

  1. 打开电脑上的记事本(Windows)或者文本编辑(Mac)
  2. 把下面的代码全选复制进去
  3. 保存文件的时候,把文件名改成比如countdown.html(注意后缀必须是.html,不能是.txt
  4. 双击这个.html文件,就能在浏览器里打开使用了

完整代码在这里

<!DOCTYPE html>
<html>
<head>
    <title>弹窗倒计时器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            padding: 20px;
            width: 300px;
            margin: 0 auto;
        }
        .timer-display {
            font-size: 48px;
            margin: 20px 0;
            color: #333;
        }
        .btn-group {
            margin-bottom: 20px;
        }
        button {
            padding: 10px 20px;
            font-size: 18px;
            margin: 0 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h2>选择倒计时时长</h2>
    <div class="btn-group">
        <button onclick="startCountdown(20)">20分钟</button>
        <button onclick="startCountdown(30)">30分钟</button>
    </div>
    <div class="timer-display" id="timer">00:00</div>

    <script>
        let countdownInterval;

        function startCountdown(minutes) {
            // 清除之前的倒计时(如果有的话)
            clearInterval(countdownInterval);
            let totalSeconds = minutes * 60;

            countdownInterval = setInterval(() => {
                totalSeconds--;
                // 计算分钟和秒数
                const mins = Math.floor(totalSeconds / 60);
                const secs = totalSeconds % 60;
                // 格式化为MM:SS,不足两位补0
                const display = `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
                document.getElementById('timer').textContent = display;

                // 倒计时结束
                if (totalSeconds <= 0) {
                    clearInterval(countdownInterval);
                    // 弹出新窗口显示文本
                    window.open('', '_blank', 'width=400,height=200').document.write('<h2>时间到啦!</h2><p>可以开始下一项任务了 😊</p>');
                }
            }, 1000);
        }
    </script>
</body>
</html>

自定义小提示(可选)

如果你想修改结束时弹窗里的文字,找到代码里的<h2>时间到啦!</h2><p>可以开始下一项任务了 😊</p>,把这段换成你想要的纯文本就行——比如改成<p>休息时间结束,继续专注!</p>都可以。

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

火山引擎 最新活动