HTML:
<div class="countDown"> <i class='hour1'></i><i class="hour2"></i>: <i class='minute1'></i><i class='minute2'></i>: <i class='second1'></i><i class='second2'></i> </div>
JS:
function timePoor(){ $('.countDown').each(function(){ var str = ''; var time = []; var bad = $(this).attr('second')?parseInt($(this).attr('second')):0;//时间差秒数 var badHours = Math.floor(bad/(3600)); //差值小时 if(badHours>24){ badHours = Math.floor(badHours/24); $(this).html('还剩余'+badHours+'天'); }else{ time.push(badHours); //计算相差分钟数 var mMs = bad%(3600); //计算小时数后剩余的毫秒数 var badMinutes = Math.floor(mMs/(60));//差值分钟 time.push(badMinutes); //计算相差秒数 var ms = mMs%(60); //计算分钟数后剩余的毫秒数 var badSeconds = Math.round(ms);//差值秒 time.push(badSeconds); //转成字符串 for(var i = 0;i<time.length;i++){ var str1 = time[i].toString(); if(str1.length < 2){ str += 0+str1; }else{ str += str1; } } $(this).find('.hour1').text(str[0]); $(this).find('.hour2').text(str[1]); $(this).find('.minute1').text(str[2]); $(this).find('.minute2').text(str[3]); $(this).find('.second1').text(str[4]); $(this).find('.second2').text(str[5]); } }) snatchDownTime();//倒计时 function snatchDownTime(){ $('.countDown').each(function(){ var $this = $(this); if($this.children('i').length==0){ return true;//结束本次循环进入下一次循环 } var i = $this.children('i'); var timeArry = []; i.each(function(){ timeArry.push($(this).text()); }); var hour = parseInt((timeArry[0]+timeArry[1]));//时 var minute = parseInt(timeArry[2]+timeArry[3]);//分 var second = parseInt(timeArry[4]+timeArry[5]);//秒 var timer = setInterval(function(){ second--;//秒 if(second<0){ second = 59; minute--;//分 if(minute<0){ minute = 59; hour--;//时 if(hour<0){//如果小时数为负数,则关闭计时器 clearInterval(timer); }else{//检测剩余时间是否为负,不为负数才继续进行显示 time($this,hour,'.hour1','.hour2'); time($this,minute,'.minute1','.minute2'); } }else{ time($this,minute,'.minute1','.minute2'); time($this,second,'.second1','.second2'); } }else{ time($this,second,'.second1','.second2'); } },1000); function time($this,num,ele1,ele2){//显示时间方法 var seconds; if(num>9){ seconds = num + ''; }else{ seconds = 0+''+ num; } $this.find(ele1).text(seconds[0]); $this.find(ele2).text(seconds[1]); } }); } }