PHP
·
发表于 5年以前
·
阅读量:8417
本文实例讲述了JS秒杀倒计时功能。分享给大家供大家参考,具体如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body onload="miaosha();">
<p class="tit_right" style="">
<span id="d" style="">00</span>天
<span id="h" style="">00</span>时
<span id="m" style="">00</span>分
<span id="s" style="">00</span>秒
</p>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
var timer = null;
// 秒杀函数
function miaosha(year, month, day, hour, minute, second) {
// 剩余时间:设定的-当前的
var leftTime = (new Date(year, month - 1, day, hour, minute, second)) - (new Date());
// parseInt()返回一个整数。得出剩余的时分秒
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) {
alert("快点!");
clearTimeout(timer);
}
else {
// 格式的转化
days = fix(days, 2);
hours = fix(hours, 2);
minutes = fix(minutes, 2);
seconds = fix(seconds, 2);
// 递归调用 注意:比当前时间大!
timer = setTimeout("miaosha(2019,09,05,10,56,00)", 1000); //// 设置开始的时间
// 设置时分秒
document.getElementById("h").innerHTML = hours;
document.getElementById("m").innerHTML = minutes;
document.getElementById("s").innerHTML = seconds;
document.getElementById("d").innerHTML = days;
}
}
//fix函数:数字加0
function fix(num, length) {
console.log(num);
// 数字转化为字符串 进行拼接
return num.toString().length<length?'0'+num:num;
}
</script>