3

わかりました、リアルタイム時間が必要な Web サイトがあるとしましょう。

例 :

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

1 秒ごとに時間:分:秒が更新されます。

私が考えていることは、interval function長いプールを実行し、60 までの場合に秒 +1 を追加してから、m に +1 を追加し、時間と同じです。しかし、すでにこの問題を解決する機能はありますか?

21:12:52これを毎秒更新するjavascriptで動く本物の時計にするにはどうすればよいですか?

私はGoogle、stackoverflowを検索しています。それらの多くは、JavaScriptから現在のリアルタイムの日時を作成する方法を教えてくれます。しかし、既存の時代からのものはありません。ある場合は、リンクを挿入してください。

4

5 に答える 5

8

これは次のように簡単です。

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();
于 2012-06-07T12:03:43.310 に答える
2

時を刻むリアルタイム クロックが必要な場合は、「フリップ クロック」を作成したときに使用したコードを見てください。各数字を個別の数字に分割して、時計内のグラフィック配置に使用しますが、それを削除すると、更新されるテキストだけになります.

Javascript フリップ クロック

于 2012-11-08T13:58:24.510 に答える
2

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>

于 2016-06-08T05:32:48.817 に答える
2

非常に高い忠実度が必要ない場合は、次の方法を使用できます。

​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

更新: コメントによると、更新する要素は 1 つと複数だけではなく、コードは 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);
于 2012-06-07T12:19:58.847 に答える