当用户在 JavaScript 中选择新时间时,继续单击时钟
Continue a clicking clock when user chooses new time in JavaScript
我在使用Vanilla Javascript构建时钟时遇到了一个问题。 我得到的当前时间很好,但我希望用户能够设置自己的时间。用户想要的时间从三个输入字段中获取,并作为可选的参数(updateH,updateM,updateS
)传递给下面的函数:
function updateTime(updateH,updateM,updateS){
updateH = updateH || false; updateM = updateM || false; updateS = updateS || false;
today = new Date();
if (updateH != false || updateM != false || updateS != false) {
today.setHours(updateH);
today.setMinutes(updateM);
today.setSeconds(updateS);
}
h = addLeadingZeroes(today.getHours()); //Today's time (hours)
m = addLeadingZeroes(today.getMinutes()); //Today's time (minutes)
s = addLeadingZeroes(today.getSeconds()); //Today's time (seconds)
day = getDay().toUpperCase(); //Today's date (day)
date = today.getaDmante(); //Today's date (date)
month = getMonth().toUpperCase(); //Today's date (month)
time24H = h + ":" + m + ":" + s;
drawWatch();
setTimeout(updateTime, 1000);
}
updateTime();
此功能每秒运行一次(1000ms),因此时钟在一秒后重置为当前时间,使用户选择的时间消失。
有没有办法将时间更新到用户传递的时间,然后使用新时间继续时钟滴答作响?例如:
时钟显示"12:00:00",然后用户输入时间"13:30:00",现在时钟从"13:30:01...13:30:02....13:30:03...ETC"开始继续滴答作响。
非常感谢您的帮助!
当用户设置他们的时间时,计算他们的时间和当前时间之间的差值,存储此值。然后,每次您要重绘手表时,只需获取新的当前时间,减去存储的差异并重新绘制手表。
就我个人而言,我会创建一个名为"Watch"的新原型,并在此对象中执行您想要的所有操作。
/* Create a "Watch" prototype */
function Watch(hours, minutes, seconds, drawInterval){
var t = this;
this.offset = 0;
this.drawInterval = drawInterval || 1000;
this.setTime = function(hours, minutes, seconds){
var now = new Date().getTime();
var theirTime = new Date();
if(hours) theirTime.setHours(hours);
if(minutes) theirTime.setMinutes(minutes);
if(seconds) theirTime.setSeconds(seconds);
this.offset = now - theirTime.getTime();
};
this.getTime = function(){
var d = new Date( new Date() - this.offset );
return d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
};
this.draw = function(elementID){
function draw(){
document.getElementById(elementID).innerHTML = t.getTime();
setTimeout(draw, t.drawInterval);
};
draw();
};
this.setTime(hours, minutes, seconds); // Initialize
}
/* Create an instance of the "Watch" prototype */
var W = new Watch();
/* Draw the watch to the DOM */
W.draw("watch");
/* Set the Users Time */
W.setTime(12,45,30); // 12:45:30
<div id='watch'></div>
相关文章:
- Java脚本时间添加
- Json数据包含日期和时间格式
- 如何根据时间运行不同的脚本
- 用每小时的差值填充数组/列表-从下拉列表中给定两个时间值
- 在wordpress一定时间后更改自定义字段
- 更改angularjs中的日期-时间格式
- 将当前时间添加到我的页面上的特定部分
- 门户网站:当地时间有多有用
- 显示时间的脚本
- 如何在窗体打开时从javascript倒计时计时器值中节省时间
- 通过JSON&比较时间
- Javascript时间轨迹
- 将日期时间作为 JSON 发送将无法在我的视图中正确显示
- 将日期时间从json转换为可读格式
- 高库存时期时间与时区不匹配
- Canvas+svg路径动画,在路径中的特定点暂停一段时间,然后继续
- 如何停止字幕文本一段时间,然后继续
- 在执行时间循环中使用继续
- 即使在 JS 中声明后,继续的时间也已过
- 当用户在 JavaScript 中选择新时间时,继续单击时钟