实际项目中,需求一个倒计时秒杀功能,每天下午6点后,计算距离第二天上午10点的小时、分钟、秒数,计时到第二天上午10点后开启抢购功能;代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/jquery-1.11.1.min.js"></script>
</head>
<body οnlοad="leftTimer();">
<p class="tit_right" style="">
<span id="h" style="">00</span>
<span id="m" style="">00</span>
<span id="s" style="">00</span>
</p>
<p style="" id="juli"></p>
<script>
function leftTimer(year,month,day,hour,minute,second){
var newDate = new Date();
var newDate1 = new Date(year,month-1,day,hour,minute,second);
var leftTime = (new Date(year,month-1,day,hour,minute,second)) - (new Date()); //计算剩余的毫秒数
var days = parseInt(leftTime / 1000 / 60 / 60 / 24 , 10); //计算剩余的天数
var hours = parseInt(leftTime / 1000 / 60 / 60 % 24 , 10); //计算剩余的小时
var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟
var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数
if (seconds<0) {
$(".tit_right").css('display', 'none');
$("#juli").text("开始抢购");
}
else{
days = fix(days,2);
hours = fix(hours,2);
minutes = fix(minutes,2);
seconds = fix(seconds,2);
setTimeout("leftTimer(2017,2,21,11,0,0)",1000);
document.getElementById("h").innerHTML=hours;
document.getElementB
yId("m").innerHTML=minutes;
document.getElementById("s").innerHTML=seconds;
}
}
//fix函数:将1~9的1位数转换成01~09的格式
function fix(num, length) {
return ('' + num).length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : '' + num;
}
</script>
</body>
</html>
以上,在leftTimer() 函数里传参,参数为指定的日期和时间,计时就开启了!