我想创建一个通过点击激活多个倒计时的网站,其中一些具有不同的时间,其他则相同。我需要根据剩下的时间来组织它们。完成后我需要将其恢复到原来的倒计时值,这样您就可以再次点击。
我有这个:http://jsfiddle.net/arglab/m19aojmu/11/
HTML
<div id="container">
<div class="element" id="el1"><b>element 1</b> <span class="timeout">10</span> seconds</div>
<div class="element" id="el2"><b>element 2</b> <span class="timeout">1000</span> seconds</div>
<div class="element" id="el3"><b>element 3</b> <span class="timeout">100</span> seconds </div>
<div class="element" id="el4"><b>element 4</b> <span class="timeout">10</span> seconds </div>
<div class="element" id="el5"><b>element 5</b> <span class="timeout">10000</span> seconds</div>
</div>
的Javascript
function timer(selector) {
var self = $(selector);
var sec = parseInt(self.find('span.timeout').text());
console.log(sec)
order++;
var actualTime = $('span.timeout').html();
console.log("Original time " + actualTime)
self.addClass('selec').css('order',order+'');
var interval = setInterval(function() {
sec--;
console.log(sec)
if (sec >= 0) {
self.find('span.timeout').text(sec);
} else if($(this).find('span').text() <= 0) {
console.log(sec)
var text = self.find('span.timeout').text(actualTime);
console.log(actualTime)
clearInterval(interval);
}
$('.element').each(function(){
if($(this).find('span').text() == 0){
$(this).removeClass('selec');
$(this).css('order','0');
}
});
}, 1000);
}
var order = 1;
$("body").on('click', '.element', function() {
timer(this);
});
但是,我不知道如何将秒数实时转换为小时 - 分钟 - 秒。我该怎么办?感谢
答案 0 :(得分:5)
只需转换值:
var hours = Math.floor(sec / 3600);
var min = Math.floor((sec - (hours*3600)) / 60);
var seconds = Math.floor(sec % 60);
与你的文字联系起来。但是你必须测试小时或分钟是否大于零来显示描述符:
var value = seconds;
if(min > 0) {
if(min == 1) {
value = " minute " + value;
} else {
value = " minutes " + value;
}
value = min + value;
}
if(hours > 0) {
if(hours == 1) {
value = " hour " + value;
} else {
value = " hours " + value;
}
value = hours + value;
}
self.find('span.timeout').text(value);
答案 1 :(得分:1)
您可以使用除法和模数来计算小时,分钟和秒:
// total seconds
var seconds = 344234;
// calculate seconds
var s = seconds % 60;
// add leading zero to seconds if needed
s = s < 10 ? "0" + s : s;
// calculate minutes
var m = Math.floor(seconds / 60) % 60;
// add leading zero to minutes if needed
m = m < 10 ? "0" + m : m;
// calculate hours
var h = Math.floor(seconds / 60 / 60);
var time = h + ":" + m + ":" + s
JSFiddle:http://jsfiddle.net/dcfxnmxc/
答案 2 :(得分:0)
这里
var minutes = Math.floor(seconds/60);
seconds = seconds - (minutes*60);
var hours = Math.floor(minutes/60);
minutes = minutes - (hours*60);