JS实现自动倒计时

时间:2021-05-10 22:04:25
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>JS实现自动倒计时30秒后按钮才可用</title>
<meta name="keywords" content="javascript,倒计时" />
<meta name="description" content="" />

<style>
.demo{width:300px; margin:60px auto 10px auto}
@media only screen and (min-width: 420px) {
	.demo{width:500px; margin:60px auto 10px auto}
}
.demo p{line-height:36px}
.button {
	display: inline-block;
	cursor:pointer;
	outline: none;
	text-align: center;
	text-decoration: none;
	font: 16px/100% 'Microsoft yahei',Arial, Helvetica, sans-serif;
	padding: .5em 2em .55em;
	-webkit-border-radius: .5em; 
	-moz-border-radius: .5em;
	border-radius: .5em;
	color: #606060;
	border: solid 1px #b7b7b7;
	background: #ededed;
}
.button:hover {
	text-decoration: none;
	background: #fff;
}
.button:active {
	position: relative;
	top: 1px;
	color: #999;
}

</style>
</head>

<body>
<div id="header">
   <div id="logo"><h1><a href="" title=""></a></h1></div>
</div>
<div id="main">
	<h2 class="top_title"><a href=""></a></h2>
	
	<div class="demo">
	<p>示例一:要求用户阅读完条款内容才能激活按钮</p>
	<form action="" method="post" name="agree">
		<input type="submit" class="button" value="请认真查看<服务条款和声明> (30)" id="agree_btn" name="agreeb">
	</form>
	<br/>
	<br/>
	<br/>
	<p>示例二:要求用户激活短信通道向用户手机发送验证码</p>
	<form action="" method="post" name="myform">
		<input type="button" class="button" value="获取手机验证码"  id="phone_btn" name="phone" onclick="showtime(30)">
	</form>
	</div>
</div>
<script>
var secs = 30;
document.agree.agreeb.disabled=true;
for(var i=1;i<=secs;i++) {
	window.setTimeout("update(" + i + ")", i * 1000);
}
function update(num) {
	if(num == secs) {
		document.agree.agreeb.value =" 我 同 意 ";
		document.agree.agreeb.disabled=false;
	}
	else {
		var printnr = secs-num;
		document.agree.agreeb.value = "请认真查看<服务条款和声明> (" + printnr +")";
	}
}

function showtime(t){
	document.myform.phone.disabled=true;
	for(i=1;i<=t;i++) {
		window.setTimeout("update_p(" + i + ","+t+")", i * 1000);
	}

}

function update_p(num,t) {
	if(num == t) {
		document.myform.phone.value =" 重新发送 ";
		document.myform.phone.disabled=false;
	}
	else {
		printnr = t-num;
		document.myform.phone.value = " (" + printnr +")秒后重新发送";
	}
}

</script>

<div id="footer">
   
</div>

</body>
</html>