js-倒计时的设计与实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.wrap {
width: 500px;
margin: 0 auto;
background: #eee;
text-align: center;
margin-top: 50px;
}
input {
width: 100px;
}
.txt {
color: #fff;
line-height: 4;
}
.cen {
padding: 20px 0;
}
#btn {
width: 120px;
height: 120px;
margin: 0 auto;
background: #000;
font-size: 30px;
line-height: 120px;
color: #FFED00;
border-radius: 50%;
box-shadow: 0 0 6px #999;
cursor: pointer;
}
#time {
color: #0000FF;
font-size: 22px;
}
.down {
font-size: 25px;
padding-bottom: 30px;
}
.down>span {
font-size: 30px;
color: #0000FF;
}
</style>
<script type="text/javascript">
window.onload = function() {
var ptS = document.getElementsByTagName('input');
var btn = document.getElementById('btn');
var time = document.getElementById('time');
var downS = document.querySelectorAll('.down>span');
// console.log(ptS,btn,time,downS);
var timer = null;
btn.onclick = function() {
var myY = parseInt(ptS[0].value);
var myM = parseInt(ptS[1].value);
var myD = parseInt(ptS[2].value);
//设置定时时间
// console.log(isNaN(myY))
var future = new Date(myY, (myM - 1), myD, 0, 0, 0);
if (!(myM >= 1 && myM <= 12)) {
alert('1-12月份');
return 0;
}
//2020年12月1日的前一天就是 11月30
var cout = days(myY,myM,0);
if(!(myD >= 1 && myD <= cout)){
alert('当前输入'+myM+'月份天数在 1 ~ '+cout+'天范围');
return 0;
}
if (isNaN(myY) && isNaN(myM) && isNaN(myD)) {
alert('请正确输入年月日');
return 0;
}
time.innerText = myY + '年' + myM + '月' + myD + '日'
//当前时间
clearInterval(timer);
// console.log(timer)
getDatediff();
var current = null;
timer = setInterval(getDatediff, 1000);
function getDatediff() {
//获取当前时间
current = new Date();
//获得时间差
var len = future - current;
//转换秒
len /= 1000;
//天 60*60*24
var d = parseInt(len / 86400);
//时
var h = parseInt(len % 86400 / 3600);
//分
var m = parseInt(len % 3600 / 60);
//秒
var s = parseInt(len % 60);
downS[0].innerText = d;
downS[1].innerText = zero(h);
downS[2].innerText = zero(m);
downS[3].innerText = zero(s);
}
}
//补0
function zero(n) {
if (n > 0) {
return n < 10 ? '0' + n : n;
} else {
return n;
}
}
//计算当月天数
function days(year, month) {
var dayCount;
now = new Date(year, month, 0);
dayCount = now.getDate();
return dayCount;
}
}
</script>
</head>
<body>
<div class="wrap">
<h2 class="txt">倒计时</h2>
<div class="cen">
请输入:
<input type="text" name="" id="year" value="" />年
<input type="text" name="" id="month" value="" />月
<input type="text" name="" id="day" value="" />日
</div>
<div id="btn">
开始
</div>
<div class="cen">
现在距离-<span id="time">0000</span>-还剩:
</div>
<div class="down">
<span>00</span>天<span>00</span>小时<span>00</span>分<span>00</span>秒
</div>
</div>
</body>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634796.html