项目中用到了,简单整理在这
更新:
一开始从服务器获取的是时间点,然后根据本地时间求得差值显示倒计时,一开始这么做我是内心拒绝的(这样修改本机时间就会显示正在抢购了,但是无法下单后台有控制),但是接口是这么给的,而且抢购活动页以前的开发也是这么做的,所以就按照当时的接口写的,测试的时候正好测试发现了这个问题,产品拍板改!然后改成了从服务器获取时间段的方法处理倒计时。
var rushtime = $("#rushTime").attr("value");//活动状态
var longtime = $("#longTime").attr("value");//当前活动状态下的活动时长
var rushdiscount = $("#rushDiscount").attr("value");//折扣
var begintoend = $("#beginToEnd").attr("value");//活动从开始到结束的全部持续时间
var countprice = $("#countprice").attr("value");//价格
if(rushtime == 1 || rushtime == 2){
//活动未开始,活动进行中
countDown(longtime,rushtime,begintoend);
}else if(rushtime == 3){
//活动已结束
$("#qianggou").show().html("活动已结束");
}else{
//没有活动
$("#qianggou").hide();
}
function countDown(longtime,rushtime,begintoend){
var time = longtime;
time = parseInt(time / 1000);
var day = Math.floor(time / (60*60*24));
time -= day * (60*60*24);
var hour = Math.floor(time /(60*60));
time -= hour * (60*60);
var minute = Math.floor(time / 60);
var second = time - (minute * 60);
if(day<10){
if(day<0 && rushtime == 1){
// 切换到正在抢购
rushtime = 2;
window.setTimeout(function(){countDown(begintoend,rushtime,begintoend);},1000);
}else if(day<0){
$("#qianggou").show().html("活动已结束");
$(".preprice1").html("").hide();
return;
}else{
day="0"+day;
}
}
if(hour<10){
hour="0"+hour;
}
if(minute<10){
minute="0"+minute;
}
if(second<10){
second="0"+second;
}
if(rushtime == 2){
$(".preprice1 i").html((countprice*rushdiscount).toFixed(2));
$(".preprice1").show();
}
if(rushtime == 1 && day==0&&hour==0&&minute==0&&second==1){
$("#qianggou").show().html("距离抢购还有 "+day+"天"+hour+"时"+minute+"分"+second+"秒");
rushtime = 2;
window.setTimeout(function(){countDown(begintoend,rushtime,begintoend);},1000);
}else if(rushtime == 1){
$("#qianggou").show().html("距离抢购还有 "+day+"天"+hour+"时"+minute+"分"+second+"秒");
longtime = longtime-1000;
window.setTimeout(function(){countDown(longtime,rushtime,begintoend);},1000);
}else if(day==0&&hour==0&&minute==0&&second==0){
$("#qianggou").show().html("活动已结束");
$(".preprice1").html("").hide();
return;
}else{
$("#qianggou").show().html("限时抢购剩余 "+day+"天"+hour+"时"+minute+"分"+second+"秒");
longtime = longtime-1000;
window.setTimeout(function(){countDown(longtime,rushtime,begintoend);},1000);
}
}
旧的代码
//dateend是活动结束日期事件戳
function countDown(dateend){
var now = Date.parse(new Date());
var str = dateend;
var target = Date.parse(new Date(str));
var time = target - now;
time = parseInt(time / 1000);
var day = Math.floor(time / (60*60*24));
time -= day * (60*60*24);
var hour = Math.floor(time /(60*60));
time -= hour * (60*60);
var minute = Math.floor(time / 60);
var second = time - (minute * 60);
if(day<10){
if(day<0){
$("#buy").html("活动已结束");
return;
}else{
day="0"+day;
}
}
if(hour<10){
hour="0"+hour;
}
if(minute<10){
minute="0"+minute;
}
if(second<10){
second="0"+second;
}
if(day==0&&hour==0&&minute==0&&second==0){
$("#buy").html("活动已结束");
}else{
$("#buy").html("限时抢购剩余"+day+"天"+hour+"时"+minute+"分"+second+"秒");
}
window.setTimeout(function(){countDown(dateend);},1000);
}
网友评论