欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

javascript 学习笔记(四) 倒计时程序代码_基础知识

程序员文章站 2022-06-15 17:28:08
...
首先看全部完整代码:

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

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








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 outStr = "距离"+deadtime.value+"已有"+countDay+"天"+countHour+"小时"+countMinute+"分"+countSecond+"秒";
} else {
outStr = "距离"+deadtime.value+"还差"+countDay+"天"+countHour+"小时"+countMinute+"分"+countSecond+"秒";
}
var showTime = document.getElementById("showTime");
showTime.innerHTML = outStr;
}