HTML+CSS+JavaScript:验证码60秒倒计时按钮

一、需求

1、打开浏览器时,按钮禁用,按钮内容为60秒倒计时

2、倒计时结束时,按钮禁用被取消

二、应用场景

1、60秒内不得重新发送验证码

2、我已阅读用户协议(5s)

三、完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>倒计时按钮</title>
</head>
<body>
    <button disabled>倒计时:60秒</button>
    <script>
        const button=document.querySelector('button')
        let i=60
        let timer=setInterval(()=>{
            i--
            button.innerHTML=`倒计时:${i}秒`
            if(i===0){
                clearInterval(timer)
                button.disabled=0 //0:取消按钮的禁用
            }
        },1000)
    </script>
</body>
</html>

 

四、注意事项

if判断语句一定要放在间歇函数的里面,否则无法终止定时器。

因为如果判断语句放在间歇函数外,判断语句作为同步任务会被放入执行栈中,程序运行时立刻执行且只执行一次。而间歇函数作为异步任务被放入任务队列中等待执行。

相反地,判断语句放在间歇函数里,每隔一秒,都会进行一次判断,直到i为0时终止倒计时。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例代码,用于使用HTML+CSS+JS实现发送验证码功能: HTML代码: ```html <form> <label for="phone">手机号:</label> <input type="tel" id="phone" name="phone" required> <button type="button" id="send-code">发送验证码</button> <br> <label for="code">验证码:</label> <input type="text" id="code" name="code" required> <button type="submit">提交</button> </form> ``` CSS代码: ```css form { display: flex; flex-direction: column; align-items: center; } input[type="tel"] { padding: 8px; margin: 8px; width: 200px; border-radius: 4px; border: 1px solid #ccc; } button { padding: 8px; margin: 8px; border-radius: 4px; border: none; cursor: pointer; } #send-code { background-color: #4CAF50; color: white; } #send-code:disabled { background-color: #ccc; cursor: not-allowed; } #code { width: 100px; } ``` JS代码: ```js const phoneInput = document.getElementById('phone'); const sendCodeButton = document.getElementById('send-code'); const codeInput = document.getElementById('code'); let countdown = 60; let countdownTimer; function startCountdown() { countdownTimer = setInterval(() => { countdown--; sendCodeButton.textContent = `重新发送 (${countdown}s)`; if (countdown === 0) { clearInterval(countdownTimer); sendCodeButton.textContent = '发送验证码'; sendCodeButton.disabled = false; countdown = 60; } }, 1000); } sendCodeButton.addEventListener('click', () => { // TODO: 发送验证码 sendCodeButton.disabled = true; startCountdown(); }); document.querySelector('form').addEventListener('submit', (event) => { event.preventDefault(); // TODO: 提交验证码 }); ``` 在上面的代码中,我们使用了`input`元素的`type="tel"`属性来限制用户只能输入手机号码。我们还设置了一个计时器来处理重新发送验证码倒计时。当用户点击发送验证码按钮时,我们会禁用该按钮并开始计时器。当倒计时结束时,我们会重置按钮状态并重新启用该按钮。在表单提交时,我们可以使用相关的代码来验证和提交验证码。注意,这个示例只是一个基本的框架,具体实现可能因需求而异。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值