知识点:定时器 setInterval
setInterval(函数,毫秒):每隔指定毫秒重复执行函数,返回定时器IDclearInterval(定时器ID):停止定时器 场景:阅读协议倒计时,倒计时结束按钮启用,才可点击访问页面。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm27.aspx.cs" Inherits="WebApplication1.WebForm27" %>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
<script type="text/javascript">
var time = 5;
var idset;
$(function () {
run();
idset = setInterval(run, 1000);
});
function run()
{
if (time>0) {
$('#but').val("请认真阅读说明(" + time + ")秒");
time--;
}
else {
$('#but').val("申请");
$('#but').attr("disabled", false);
clearInterval(idset);//清除定时器,停止循环
}
}
</script>
</head>
<body>
<input id="but" type="button" value="" disabled="disabled" />
</body>
</html>
Code language: HTML, XML (xml)
说明:
- 页面加载完成,开启定时器,1000毫秒(1秒)执行一次
run() - 倒计时大于0:按钮显示剩余秒数,按钮禁用
- 倒计时到0:按钮文字改为【申请】,解除禁用,调用
clearInterval停止定时器优化:原代码把setInterval写在外面会重复启动定时器,调整放到$(function)内部。
Previous: 完成一个加法功能使用到类型转换功能
Next: 实现搜索框字体提示功能