倒计时

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="time/laydate.js"></script>
<style>
	*{margin: 0;padding: 0;}	
	body{background:#000;color:#FFF;}
	ul{list-style:none;}
	.fl{float:left;}
	#wrap{600px;height: 300px;border:2px solid green;margin:30px auto;border-radius:10px;}
	#wrap .title{text-align:center;font-size:40px;line-height:100px;height:100px;}
	#wrap .end_wrap{height:30px;margin:0 auto;380px;height:30px;}
	#wrap .end_wrap span{color:red; font-size:28px;	line-height:28px;}
	#wrap .end_wrap input{height:28px;250px;margin-left: 10px;margin-top: -5px;}
	#wrap button{margin:20px auto;display: block; 150px;height:30px;line-height:30px;color:green;line-height:30px; }
	#wrap ul {300px;height:40px;margin:10px auto;}
	#wrap ul li{float:left;30px;text-align:center;height:40px;line-height:40px;}
	#wrap ul li.time{color:red;font-size:30px;}
</style>
</head>
<body>
<div id="wrap">
	<div class="title">倒计时</div>
	<div class="end_wrap">
		<div class="fl" >结束时间:</div>
		<div class="fl">
			<input id="endTime" onclick="laydate({istime: true, format: 'YYYY/MM/DD hh:mm:ss'})"  type="text">
		</div>
	</div>
	<div><button onclick="test()">开始计时</button></div>
	<div>距离当前时间还有:</div>
	<ul>
		<li id="d" class="time"></li>
		<li>天</li>
		<li id="h" class="time"></li>
		<li>时</li>
		<li id="m" class="time"></li>
		<li>分</li>
		<li id="s" class="time"></li>
		<li>秒</li>
	</ul>
</div>	
<script>
	
	function test(){
		// 获取对象
		var endTimeObj = document.getElementById('endTime');

		// 判断有木有 输入 结束时间
		if(!endTimeObj.value){
			alert('请输入结束时间!');
			return false;
		}

		// 当前时间 毫秒数
		var nowTime = new Date().getTime();

		// 结束时间 对象
		var endTime = new Date(endTimeObj.value).getTime();

		// 时间差
		var t = endTime - nowTime

		//时间必须在今天之后!
		if(t<=0){
			alert('时间必须在今天之后!')
			// 在 JS 中 函数return 后面的代码不执行
			return false;
		} 

		// 转化格式
		// 天
		var d = Math.floor(t/1000/60/60/24);
		// 小时
		var h = Math.floor(t/1000/60/60%24);
		// 分
		var m = Math.floor(t/1000/60%60);
		// 秒
		var s = Math.floor(t/1000%60);

		// alert(h);
		
		// 把时间写到容器
		document.getElementById('d').innerHTML = d;
		document.getElementById('h').innerHTML = h; 
		document.getElementById('m').innerHTML = m; 
		document.getElementById('s').innerHTML = s;

		setTimeout(test,1000);

	}

</script>
</body>
</html>

  

原文地址:https://www.cnblogs.com/-qiang/p/5802194.html