使用 JavaScript 在 div 中用现有时间制作一个实时时钟



好吧,假设我们有一个需要实时的网站;

例:

<div id="updatetime">21:12:52</div>

每秒更新小时:M:秒。

我想到的是使用 interval function 做长池并将 sec +1 如果添加到 60,然后将 + 1 添加到 m 并且与小时相同。 但是有没有已经解决这个问题的功能?

你如何使这个21:12:52一个移动的真实时钟,JavaScript每秒更新一次?

我搜索了Google,StackOverflow,其中许多都告诉我们如何从JavaScript制作当前的实时日期时间。 但没有来自现有时间。 如果有,请插入链接。

它可以像

这样简单:

setInterval(function(){
    document.getElementById("updatetime").innerHTML = (new Date()).toLocaleTimeString();
}, 1000);

或者使用其他 Date 方法来微调输出。

更新

我现在才意识到 OP 问的不是用当前时间递增元素,而是用预定时间递增元素。

这不那么微不足道,但这里有一个解决方案应该符合原始问题:

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();

如果你不需要非常高的保真度,你可以这样使用:

​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);

如果你想与当前的计算机时钟更加同步,那么我建议你使用setTimeout,并根据适当的经过时间来调整delay参数。

更新

:由于注释,似乎要更新的元素不仅是一个和多个,并且代码使用的是jQuery。这里有一种方法适用于多个元素,使用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);

如果你的实时时钟滴答作响,看看我在创建"翻转时钟"时使用的代码。我将每个数字拆分为一个单独的数字,用于时钟内的图形放置,但如果您将其剥离,您将只看到更新的文本。

Javascript 翻转时钟

使用 HTML canvas

法典:

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>

你可以用下面的代码来做

<!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>

最新更新