我目前正在拍卖网站上工作,我需要从初始HTML值显示倒计时,页面上会有几个不同的实例。
该值只是一个以PHP格式解析的文本字符串,格式为hh:mm:ss。
我发现了大量不同的倒计时脚本,但它们主要用于图形表示,并且只使用JS / jQ中的初始值设置。
<span class="countdown">11:55:12<span>
我只是在寻找一个简单的解决方案,倒数到零,如果需要回调一些种类。我尝试了很多脚本,但似乎无法在多个元素上获得基本的文本功能。
任何帮助表示赞赏!
答案 0 :(得分:0)
有多种方法可以做到这一点,但这里有一个简单的jQuery函数方法......
(function($){
$.fn.extend({
startTimer:function(){
// countdown elements
var _this = this;
// for padding numbers with leading zero
Number.prototype.pad=function(){
return (this<10?'0':'')+this;
}
var computeAndDisplay=function(){
//loop through countdown elements
$(_this).each(function(){
// get timestamp from ID attribute
var timestamp = parseInt($(this).attr('id').split('_').pop())*1000;
var differance = timestamp - new Date().getTime();
var hours = 0;
var minutes = 0;
var seconds = 0;
// if there is a positive difference
if(differance > 0){
//hours
if(differance >= 3600000){
hours = Math.floor(differance/3600000);
}
//minutes
if(differance >= 60000){
minutes = Math.floor(differance/60000)%60;
}
//seconds
if(differance >= 0){
seconds = Math.floor(differance/1000)%60;
}
$(this).html(hours.pad()+":"+minutes.pad()+":"+seconds.pad());
}else{
// if there is no positive difference, timer is done and you can
// do whatever to that countdown element here
}
});
};
//start timer
setInterval(computeAndDisplay,1000);
}
});
})(jQuery);
此方法仅依赖于循环多次倒计时的一个setInterval函数,而不是对每个倒计时实例使用单独的setInterval调用。但是,我们应该在每个html元素的ID中保留初始时间戳值,这样我们每次都可以检索它。
<div class="countdown" id="cd_1_1332794014"></div>
<div class="countdown" id="cd_2_1332698014"></div>
<div class="countdown" id="cd_3_1332699014"></div>
ID的最后一位是来自php的unix时间戳,中间部分与功能无关,但存在以保持ID唯一。
要让计时器开始,你只需要打电话......
$(document).ready(function(){
$('.countdown').startTimer();
});