【发布时间】:2014-03-14 05:38:51
【问题描述】:
如果您知道 14dayz,您就会看到那些项目/任务计时器。它们包含一个保存时间 (00:00) 的输入框和一个可以启动或暂停计时器的切换按钮。当计时器处于活动状态时,输入中的值会每秒更新一次。
当您第二天回访时,时间将从数据库中加载,您可以从停止的地方开始计时。
但是,您可能会在开始处理项目/任务时忘记点击按钮。这就是为什么计时器允许您手动将输入值编辑为 00:45 之类的内容。当您在输入值后点击按钮时,它只是从该点开始。
在我的项目中,我已经使用jquery.timer.js,所以我想也将它用于此类计时器。
我的 HTML 是这样构建的:
<div class="input-append">
<input class="span2" id="time" type="text" value="00:20:00">
<button class="btn btn-toggle-timer" type="button"><i class="icon-time"></i></button>
</div>
当它从 00:00 或存储的时间 (db) (如 00:20)开始时,它可以正常工作。 但是,如果我暂停计时器,编辑值并再次播放,它会跳回到我暂停时输入的时间。 这似乎是 jQuery 计时器插件的默认行为。我已经拍摄了几张照片来重建他们的 example1(秒表),所以它符合我的需要。现在我开始相信黑魔法与它有关。
我尝试的最后一个js:
var Example1 = new (function() {
var $stopwatch, // Stopwatch element on the page
incrementTime = 1000, // Timer speed in milliseconds
currentTime, // Current time in hundredths of a second
updateTimer = function() {
$stopwatch.val(formatTime(currentTime));
currentTime += incrementTime / 10;
Example1.Timer.remaining = currentTime;
},
init = function() {
$stopwatch = $("#time");
currentTime = unformatTime();
console.log(currentTime);
Example1.Timer = $.timer(updateTimer, incrementTime, false);
};
this.play = function(reset) {
if(!this.Timer.isActive) {
if(reset) {this.Timer.setTimer();}
else {this.Timer.setTimer(this.currentTime);this.currentTime = unformatTime();}
this.Timer.isActive = true;
}
return this;
};
this.pause = function() {
if(Example1.Timer.isActive) {
Example1.Timer.isActive = false;
Example1.Timer.remaining -= unformatTime() - Example1.Timer.last;
Example1.Timer.clearTimer();
}
return this;
};
this.toggle = function(reset) {
if(Example1.Timer.isActive) {
this.pause();
}
else if(reset) {this.play(true);}
else {
this.play();
}
return this;
};
this.resetStopwatch = function() {
currentTime = 0;
this.Timer.stop().once();
};
$(init);
});
// Common functions
function pad(number, length) {
var str = "" + number;
while (str.length < length) {str = "0" + str;}
return str;
}
function formatTime(time) {
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
}
function unformatTime() {
var timeEnd = $("#time").val();
console.log(timeEnd);
return (Number(timeEnd.split(":")[0]) * 6000) + ((Number(timeEnd.split(":")[1]) * 100) + (Number(timeEnd.split(":")[0]) / 60));
}
// Trigger for the toggle button
$(document).on('click', '.btn-toggle-timer', function(e) {
Example1.toggle();
$(this).toggleClass("btn-success").find("i").toggleClass("icon-pause icon-time");
}
我尝试设置jsFiddle,但我没有成功添加计时器插件。它不断抛出错误。
我希望有人知道我在这个问题上做错了什么。 非常感谢您的帮助。
【问题讨论】: