如何编写验证码倒计时JavaScript代码?
- 内容介绍
- 文章标签
- 相关推荐
本文共计306个文字,预计阅读时间需要2分钟。
获取验证码计时器 - 在页面加载完毕后,设置一个按钮点击事件,当点击按钮时开始计时,按钮将被禁用,并在10秒后重新启用。代码如下:
javascriptgetVarify.js // 验证码计时器window.onload=function () { var send=document.getElementById('send'); var times=10; var timer=null; send.onclick=function () { // 计时开始 send.disabled='disabled'; timer=setInterval(function () { times--; send.innerText='重新发送(' + times + ')'; if (times <=0) { clearInterval(timer); send.disabled=''; send.innerText='发送验证码'; times=10; } }, 1000); };};
getVarify.js// 验证码计时——第一种 window.onload = function () { var send = document.getElementById('send'), //按钮ID times = 10, // 别忘了改这里 timer = null; send.onclick = function () { // 计时开始 send.disabled = true; timer = setInterval(function () { times--; if (times <= 0) { send.value = '获取验证码'; clearInterval(timer); times = 5; // 别忘了改这里 send.disabled = false; } else { send.value = times + '秒后重试' send.disabled = true; } console.log(times) }, 1000); // 发送请求获取验证码 console.log("sending...") } } // 验证码计时——第二种 // 参数:倒计时秒数, 按钮jquery对象, 倒计时结束时显示的文字 // 可以放到短信发送完毕后的回调函数里 // switchMSG(60, $("#get-verify"), '获取验证码') function switchMSG(times, ele, txt) { ele.prop('disabled', true) var idT = setInterval(function() { if(times < 1) { ele.html(txt) ele.prop('disabled', false) clearInterval(idT) } else { ele.html(times+'s') times-- } }, 1000) }
本文共计306个文字,预计阅读时间需要2分钟。
获取验证码计时器 - 在页面加载完毕后,设置一个按钮点击事件,当点击按钮时开始计时,按钮将被禁用,并在10秒后重新启用。代码如下:
javascriptgetVarify.js // 验证码计时器window.onload=function () { var send=document.getElementById('send'); var times=10; var timer=null; send.onclick=function () { // 计时开始 send.disabled='disabled'; timer=setInterval(function () { times--; send.innerText='重新发送(' + times + ')'; if (times <=0) { clearInterval(timer); send.disabled=''; send.innerText='发送验证码'; times=10; } }, 1000); };};
getVarify.js// 验证码计时——第一种 window.onload = function () { var send = document.getElementById('send'), //按钮ID times = 10, // 别忘了改这里 timer = null; send.onclick = function () { // 计时开始 send.disabled = true; timer = setInterval(function () { times--; if (times <= 0) { send.value = '获取验证码'; clearInterval(timer); times = 5; // 别忘了改这里 send.disabled = false; } else { send.value = times + '秒后重试' send.disabled = true; } console.log(times) }, 1000); // 发送请求获取验证码 console.log("sending...") } } // 验证码计时——第二种 // 参数:倒计时秒数, 按钮jquery对象, 倒计时结束时显示的文字 // 可以放到短信发送完毕后的回调函数里 // switchMSG(60, $("#get-verify"), '获取验证码') function switchMSG(times, ele, txt) { ele.prop('disabled', true) var idT = setInterval(function() { if(times < 1) { ele.html(txt) ele.prop('disabled', false) clearInterval(idT) } else { ele.html(times+'s') times-- } }, 1000) }

