JS案例之3——倒计时

利用简单的数字累加循环模拟倒计时的效果,逻辑比较简单。如果大牛们有更好的办法欢迎补充。

这种效果经常用于在规定的时间做某件事。比如在1分钟之后重新发送验证码等。

案例演示:

JS案例之3——倒计时

源代码如下:

 <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" Content="text/html; charset=utf-8;">
<title> JS实现倒计时 </title>
<meta name="author" content="rainna" />
<meta name="keywords" content="rainna's js lib" />
<meta name="description" content="JS实现倒计时" />
<style>
*{margin:0;padding:0;} .m-time{width:500px;margin:100px auto;}
.m-time .btn,.m-time .btn2{display:block;width:200px;height:40px;margin:10px 0;background:#B4D174;border-radius:5px;color:#fff;text-decoration:none;text-align:center;line-height:40px;}
.m-time .btn2{opacity:.3;}
.m-time span{font-weight:bold;color:#f00;}
</style>
</head>
<body>
<div class="m-time">
<p>请输入倒计时时间:<input type="text" id="timeIpt"/></p>
<a href="" class="btn" id="sendBtn">发送</a>
<p>剩余<span id="leftTime"></span>秒</p>
</div> <script>
var timer = function(){
var setTime = function(){
var self = this;
if(!(self instanceof setTime)){
return new setTime();
}
self.sendBtn = document.getElementById('sendBtn'); //发送按钮
self.leftTime = document.getElementById('leftTime'); //显示剩余时间
self.status = true; //当为true时,发送按钮可点击
};
setTime.prototype = {
constructor: setTime,
showTime: function(time){
var self = this;
if(!!self.timerId) clearTimeout(self.timerId);
self.timerId = setTimeout(function(){
self.showTime(time);
},1000) self.leftTime.innerText = time;
self.sendBtn.className = 'btn2';
self.status = false;
time--; //倒计时结束
if(time < 0){
clearTimeout(self.timerId);
self.status = true;
self.sendBtn.className = 'btn';
}
},
init:function(){
var self = this;
self.sendBtn.onclick = function(event){
event.preventDefault();
if(self.status == true) self.showTime(document.getElementById('timeIpt').value);
}
}
} return function(){
var st = new setTime();
st.init();
}
}(); timer();
</script>
</body>
</html>
上一篇:关于beginPath()和closePath()的关系>>canvas的beginPath和closePath分析总结,包括多段弧的情况


下一篇:解决liblzo2.so缺失