需求:获得一天5个不同阶段的倒计时,为期10天。
计数时段分比为:
第一时段9:00-11:59、第二时段12:00-17:59、第三时段18:00-20:59、第四时段21:00-23:59、第五时段次日0:00-8:59,共五个时段。
简单的写了如下:见第一部分。
当然真实肯定不是这样,稍微调整一下,要从服务器获取时间的,不要相信客户端时间,见第二部分。
DOM:
<div id="txt"></div>
JS:
-----------------------------第一部分--------------------------------------------
function ShowCountDown() { var now = new Date(), year = now.getFullYear(), month = now.getMonth(), day = now.getDate(), h = now.getHours(), endDate; if (h >= 0 && h < 9) { endDate = new Date(year, month, day, 8, 59, 59); } else if (h >= 9 && h < 12) { endDate = new Date(year, month, day, 11, 59, 59); } else if (h >= 12 && h < 18) { endDate = new Date(year, month, day, 17, 59, 59); } else if (h >= 18 && h < 21) { endDate = new Date(year, month, day, 20, 59, 59); } else { endDate = new Date(year, month, day, 23, 59, 59); } var leftsecond = parseInt((endDate.getTime() - now.getTime()) / 1000); var hour = Math.floor(leftsecond / 3600); var minute = Math.floor((leftsecond - hour * 3600) / 60); var second = Math.floor(leftsecond - hour * 3600 - minute * 60); document.getElementById(‘txt‘).innerHTML = "距离此时段结束还有:" + hour + "小时" + minute + "分" + second + "秒"; countDowntimer = setTimeout(function() { ShowCountDown(); }, 1000); } ShowCountDown();
----------------------------第二部分-------------------------------
上面只是简单的测试看看的,真实要熊服务器获取时间,这样才能保证不必要的错误,稍微改写一下
function ShowCountDown(ele, startTime, endTime) { var startTimeArr = startTime.split(":"); var endTimeArr = endTime.split(":"); var startH = +startTimeArr[0], startM = +startTimeArr[1], startS = +startTimeArr[2], startDate = new Date(2017, 03, 10, startH, startM, startS).getTime(), endH = +endTimeArr[0], endM = +endTimeArr[1], endS = +endTimeArr[2], endDate = new Date(2017, 03, 10, endH, endM, endS).getTime(), leftsecond = (endDate - startDate) / 1000; var st = setInterval(function() { leftsecond -= 1; if (leftsecond == 0) { clearInterval(st); } getEndTime(leftsecond,ele); }, 1000); }function getEndTime(arg, ele) { hour = Math.floor(arg / 3600), minute = Math.floor((arg - hour * 3600) / 60), second = Math.floor(arg - hour * 3600 - minute * 60); document.getElementById(ele).innerHTML = hour + "小时" + minute + "分" + second + "秒"; }//参数一:dom元素; 参数二:用户访问页面服务器传回的时间; 参数三:服务器设置的各阶段截止时间。// 如:startTime = ‘10:23:45‘; endTime = ‘11:59:59‘ ShowCountDown(‘countdown‘, startTime, endTime);
时间: 2024-10-13 01:01:23