JQuery倒计时到特定日期

时间:2015-05-12 02:05:03

标签: jquery timer countdown

我正在试图弄清楚如何在JQuery中构建一个倒计时器,它将倒计时到一个设定的日期,一旦它到达那一天,它将显示一条消息,例如“立即可用”,代替倒计时的位置。 / p>

我做了一个动画,展示了一个例子,如果有帮助我的意思:

http://i.stack.imgur.com/qYthR.gif

任何人都可以帮助我吗?或者也许我指向一个教程或某些东西,告诉我如何做到这一点? :)

非常感谢你!

2 个答案:

答案 0 :(得分:1)

看看这个。我对代码做了评论。如果有问题,请。问候ANdré

var availableDate=new Date();
//set eg "May 12 2015 05:01:00"
availableDate.setDate(12);
availableDate.setMonth(4);//January has index 0!!!
availableDate.setFullYear(2015);
availableDate.setHours(5);
availableDate.setMinutes(1);//January has index 0!!!
availableDate.setSeconds(0);
 
var availableDateField =$("#availableDate");
availableDateField.text(availableDate);

var timeField =$("#time");

var t=setInterval(loop,1000); //(handler,intervall in ms)
function loop(){
  //get current Date (now)
  var now=new Date();
  //get difference
  var diff=availableDate - now;
  //if the time has come ;-)
  if(diff<=0){     
    clearInterval(t);
    timeField.text("Time has Come");
    return false;
  }
  //if not
  var str= "Time to wait: "+parseMs(diff);    
  timeField.text(str);
}

function parseMs(ms){
  //ToDO for you: Years, months and days :-)
  var hours = Math.floor(ms/(3600000))
  ms = ms % 3600000;
  var minutes = Math.floor(ms / 60000 );
  ms = ms % 60000;
  var seconds = Math.floor(ms / 1000);
  ms = ms % 1000;
 			
  var hoursStr = checkForZero(hours);
  var minutesStr = checkForZero(minutes);
  var secondStr = checkForZero(seconds);
 			
  var timeString = hoursStr + ":" + minutesStr + ":" + secondStr;
  return timeString;
}

function checkForZero(i){
  //write "0" before ?
  str=i+"";
  if (parseInt(i,10) < 10) str = "0" + str;
  return str;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=availableDate>
</div>
<div id=time>
</div>

0

答案 1 :(得分:0)

这里有一些小东西我很快就掀起了。 http://codepen.io/anthony-dandrea/pen/MwKxod?editors=101

您只需更改日期即可查看&#34;立即可用!&#34;

&#13;
&#13;
$(document).ready(function() {
  var countdownHtml = $('#countdown');
  var today = new Date;
  var offerDate = new Date(2015, 5, 1); // June 1st, 2015
  if (offerDate > today) {
    var timeDiff = Math.ceil(Math.abs(offerDate.getTime() - today.getTime())/864e5);
    countdownHtml.text(timeDiff+' days until available!');
  } else {
    countdownHtml.text('Available now!');
  }
});
&#13;
<p id="countdown"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;