效果图:
具体代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title倒计时title>
<style>
input {
40px;
height: 20px;
}
#remainTime{
margin-top: 30px;
font-size: 40px;
}
#remainTime span {
display: inline-block;
100px;
height: 20px;
color: red;
}
</style>
</head>
<body>
<form>目的日期:
<input type="text" id="year"><span>年</span>
<input type="text" id="month"><span>月</span>
<input type="text" id="day"><span>日</span>
<input type="text" id="hour"><span>时</span>
<input type="text" id="minute"><span>分</span>
<input type="text" id="second"><span>秒</span>
<input type="button" value="提交" οnclick="show()">
</form>
<div id="remainTime">倒计时:
<span id="one"></span>天
<span id="two"></span>时
<span id="three"></span>分
<span id="four"></span>秒
</div>
</body>
<script>
function show() {
//1.获取自己输入的目的时间
var oYear = document.getElementById('year').value;
var oMonth = document.getElementById('month').value - 1;
var oDay = document.getElementById('day').value;
var oHour = document.getElementById('hour').value;
var oMinute = document.getElementById('minute').value;
var oSecond = document.getElementById('second').value;
var funtureDate = new Date(oYear, oMonth, oDay, oHour, oMinute, oSecond);
// var funtureDate = new Date('2019/06/07 08:00:00');
//2.设置定时器
setInterval(function () {
//3.获取现在的时间
var presentDate = new Date();
//4.获取时间戳
var funtureTime = funtureDate.getTime();
var presenTime = presentDate.getTime();
//5.获取剩余的时间戳
var allTime = funtureTime - presenTime;
//6.把毫秒转换为秒
var allSecond = parseInt(allTime / 1000);
//7.获取剩余多少天
var day = size(parseInt(allSecond / 3600 / 24));
//8.获取剩余多少小时
var hour = size(parseInt(allSecond / 3600 % 24));
//9.获取剩余多少分钟
var minute = size(parseInt(allSecond / 60 % 60));
//10.获取剩余多少秒
var second = size(parseInt(allSecond % 60));
//11.注入:
document.getElementById('one').innerHTML = day;
document.getElementById('two').innerHTML = hour;
document.getElementById('three').innerHTML = minute;
document.getElementById('four').innerHTML = second;
}, 1000);
//如果数>=10,则在前面补0
function size(num) {
return num < 10 & num >= 0 ? '0' + num : num;
}
}
</script>
</html>