利用JS实现短信验证码倒计时案例
本章教程利用JS实现发送短信倒计时案例,这个需求在实际开发过程很常见。
目录
一、程序代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送短信验证码倒计时案例</title>
<style type="text/css">
#demo {
margin-top: 200px;
text-align: center;
}
</style>
</head>
<body>
<div id="demo">
<input type="text" name="code" id="code">
<button id="sendCode" onclick="sendCode()">获取验证码</button>
</div>
<script type="text/javascript">
var btn = document.querySelector("#sendCode");
var interval;
var times = 10;
function sendCode() {
interval = setInterval(function () {
if (times > 0) {
btn.disabled = true;
btn.innerText = ((times < 10 ? "0" + times : times) + "s后重新获取");
times--;
} else {
clearInterval(interval);
btn.disabled = false;
btn.innerText = "获取验证码";
}
}, 1000);
}
</script>
</body>
</html>