很多网站在注册的时候都会发送验证码到用户的手机上,发送之后会显示倒计时效果,如果超出时间,则点击按钮重新发送,这种效果的实现主要利用了JavaScript中的计时器,其代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>发送验证码</title>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css" />
<script type="text/javascript" src="bootstrap/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.js"></script>
</head>
<body>
<div style="margin-left: 400px;margin-top: 400px;">
<input type="button" id="btn" class="btn btn-info btn-lg" value="获取验证码" />
</div>
<script type="text/javascript">
var button = document.getElementById('btn');
button.onclick = function() {
button.disabled = 'disabled';
var time = 60;
var timer = setInterval(function() {
if (time == -1) {
clearInterval(timer)
button.disabled = '';
button.value = '获取验证码';
} else {
button.value = time + '秒后重新获取';
time--;
}
}, 1000)
}
</script>
</body>
</html>