当前位置:主页 > >

javascript 学习笔记(四) 倒计时程序代码

时间:2023-03-01 15:11:07 | 栏目: | 点击:

首先看全部完整代码:

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]

html部分代码:
可在文本框中输入倒计时的时间,如果当前时间小于截止时间,则正常返回,反之,则返回距离截止日期到现在的时间
复制代码 代码如下:

<p>
<label for="deadline">截止日期</label>
<input type="text" value="2011-06-11" id="deadline" />
<input type="button" value="开始倒计时" onclick="window.setInterval('countDown(\'deadline\')', 1000)" />
</p>
<p id="showTime"></p>

javascript部分代码:
复制代码 代码如下:

function countDown(endDate) {
var now = new Date();
var deadtime = document.getElementById(endDate);
var deadline = new Date(deadtime.value);
//本地时间与格林威治标准时间 (GMT) 的分钟差
var timeDiff = now.getTimezoneOffset();
//此处有些不解,如果把分钟差转化成毫秒应该是timeDiff*60*1000,但是这样返回的数据不正确!
var leave = Math.abs(deadline.getTime() - now.getTime() + timeDiff*60);
var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var countDay = Math.floor(leave/day);
//var countHour = Math.floor((leave - day*countDay)/hour); 两种计算思路
var countHour = Math.floor(leave/hour - countDay*24);
var countMinute = Math.floor(leave/minute) - countDay*24*60 - countHour*60;
var countSecond = Math.floor(leave/1000) - countDay*24*60*60 - countHour*60*60 - countMinute*60;
var outStr = "";
if(deadline < now) {
outStr = "距离"+deadtime.value+"已有"+countDay+"天"+countHour+"小时"+countMinute+"分"+countSecond+"秒";
} else {
outStr = "距离"+deadtime.value+"还差"+countDay+"天"+countHour+"小时"+countMinute+"分"+countSecond+"秒";
}
var showTime = document.getElementById("showTime");
showTime.innerHTML = outStr;
}

您可能感兴趣的文章:

相关文章