[英]make a live clock with existing time in div with javascript
ok lets say we have a website that need a realtime time; 好吧,我们假设我们有一个需要实时的网站;
example : 例如:
<div id="updatetime">21:12:52</div>
each seconds update hours:m:second. 每秒更新小时:m:秒。
what i have in minds using the interval function
to do long pool and add the sec +1 if to 60 then add + 1 to m and same as hours. 我有什么想法使用interval function
做长池并添加秒+1如果到60然后添加+ 1到m和相同的小时。 but is there a function already solving this problem? 但有没有一个功能已经解决了这个问题?
how do you make this 21:12:52
a moving real clock with javascript that updates each seconds? 你怎么做这个21:12:52
一个移动的真正的时钟与javascript 21:12:52
更新?
i have search google, stackoverflow, many of them tells us how to make the current real time datetime from javascript. 我有搜索谷歌,stackoverflow,其中许多告诉我们如何从JavaScript进行当前的实时日期时间。 but none from an existing time. 但是现有的时间都没有。 if there is please do insert the link. 如果有请请插入链接。
It can be as easy as this: 它可以像这样简单:
setInterval(function(){
document.getElementById("updatetime").innerHTML = (new Date()).toLocaleTimeString();
}, 1000);
Or use the other Date methods to fine-tune your output. 或使用其他Date方法微调输出。
Update 更新
I only now realized that OP was asking not about incrementing an element with the current time but with a predetermined time. 我现在才意识到OP不是要求用当前时间增加一个元素,而是用预定的时间。
That's less trivial, but here is a solution that should fit the original question: 这不是那么简单,但这是一个适合原始问题的解决方案:
function increment_time_element(element, delay) {
var interval, last,
time_pattern = /(\d+):(\d+):(\d+)/,
start = element.innerHTML.match(time_pattern),
then = new Date;
then.setHours (parseInt(start[1], 10) || 0);
then.setMinutes(parseInt(start[2], 10) || 0);
then.setSeconds(parseInt(start[3], 10) || 0);
function now() {
return Date.now ? Date.now() : (new Date).getTime();
}
last = now();
interval = setInterval(function () {
var current = now();
// correct for any interval drift by using actual difference
then.setTime(then.getTime() + current - last)
last = current;
element.innerHTML = then.toString().match(time_pattern)[0];
}, delay || 1000);
return {cancel: function() { clearInterval(interval) }};
}
// Usage:
var incrementing_time =
increment_time_element(document.getElementById("updatetime"));
// Then, if you want to cancel:
incrementing_time.cancel();
If you don't need a very high fidelity, you can use this way: 如果您不需要非常高的保真度,可以使用以下方式:
var container = document.getElementById("updatetime").firstChild;
var values = container.nodeValue.split(":");
// Because there is only a datetime specified, I assume is the current date
var now = new Date();
var time = new Date(now.getFullYear(), now.getMonth(), now.getDate(),
values[0], values[1], values[2]).getTime();
setInterval(function() {
time += 1000;
var date = new Date(time);
var values = [date.getHours(), date.getMinutes(), date.getSeconds()];
for (var i = 0; i < 3; i++)
if (values[i] < 10)
values[i] = "0" + values[i];
container.nodeValue = values.join(":");
}, 1000);
If you want to be more in sync with the current computer clock, then I suggest to you to use setTimeout
and adjust the delay
argument with the proper elapsed time. 如果你想与当前的计算机时钟更加同步,那么我建议你使用setTimeout
并用适当的经过时间调整delay
参数。
Update : due the comments, it seems the elements to update are not only one and multiple, and the code is using jQuery. 更新 :由于评论,似乎更新的元素不仅是一个和多个,而且代码是使用jQuery。 Here an approach that works for multiple elements using class
to identify them: 这里有一种方法适用于多个元素,使用class
来识别它们:
var containers = $(".updatetime");
var times = [];
var now = new Date();
containers.each(function(index, node) {
var values = $(node).text().split(":");
times[index] = new Date(
now.getFullYear(), now.getMonth(), now.getDate(),
values[0], values[1], values[2]).getTime();
});
setInterval(function() {
containers.each(function(index, node) {
times[index] += 1000;
var date = new Date(times[index]);
var values = [date.getHours(), date.getMinutes(), date.getSeconds()];
for (var i = 0; i < 3; i++)
if (values[i] < 10)
values[i] = "0" + values[i];
$(node).text(values.join(":"));
});
}, 1000);
If your after a realtime clock that ticks along, take a look at the code I used when I created a "flip clock". 如果您在实时时钟之后,请查看我创建“翻转时钟”时使用的代码。 I split each digit into a seperate individual digit to use for graphic placement within the clock, but if you strip it down you will have just text that updates. 我将每个数字拆分成一个单独的数字,用于在时钟内进行图形放置,但是如果你将其剥离,你将只有更新的文本。
using HTML canvas
使用HTML canvas
code: 码:
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var radius = canvas.height / 2; ctx.translate(radius, radius); radius = radius * 0.90 setInterval(drawClock, 1000); function drawClock() { drawFace(ctx, radius); drawNumbers(ctx, radius); drawTime(ctx, radius); } function drawFace(ctx, radius) { var grad; ctx.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fillStyle = 'white'; ctx.fill(); grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05); grad.addColorStop(0, '#333'); grad.addColorStop(0.5, 'white'); grad.addColorStop(1, '#333'); ctx.strokeStyle = grad; ctx.lineWidth = radius * 0.1; ctx.stroke(); ctx.beginPath(); ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI); ctx.fillStyle = '#333'; ctx.fill(); } function drawNumbers(ctx, radius) { var ang; var num; ctx.font = radius * 0.15 + "px arial"; ctx.textBaseline = "middle"; ctx.textAlign = "center"; for (num = 1; num < 13; num++) { ang = num * Math.PI / 6; ctx.rotate(ang); ctx.translate(0, -radius * 0.85); ctx.rotate(-ang); ctx.fillText(num.toString(), 0, 0); ctx.rotate(ang); ctx.translate(0, radius * 0.85); ctx.rotate(-ang); } } function drawTime(ctx, radius) { var now = new Date(); var hour = now.getHours(); var minute = now.getMinutes(); var second = now.getSeconds(); //hour hour = hour % 12; hour = (hour * Math.PI / 6) + (minute * Math.PI / (6 * 60)) + (second * Math.PI / (360 * 60)); drawHand(ctx, hour, radius * 0.5, radius * 0.07); //minute minute = (minute * Math.PI / 30) + (second * Math.PI / (30 * 60)); drawHand(ctx, minute, radius * 0.8, radius * 0.07); // second second = (second * Math.PI / 30); drawHand(ctx, second, radius * 0.9, radius * 0.02); } function drawHand(ctx, pos, length, width) { ctx.beginPath(); ctx.lineWidth = width; ctx.lineCap = "round"; ctx.moveTo(0, 0); ctx.rotate(pos); ctx.lineTo(0, -length); ctx.stroke(); ctx.rotate(-pos); }
<canvas id="canvas" width="400" height="400" style="background-color:#333"> </canvas>
you can do it with below code 你可以用下面的代码来做
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.