如何在淡入后重复显示当前时间

How to repeatedly display the current time right after fadein?

本文关键字:显示 时间 淡入      更新时间:2023-09-26

以下代码生成一个计时器,显示fadein之后的当前时间。所以看起来很糟糕。如何在渐变后重复显示当前时间?

<!doctype html>
<html>
<head>
    <title>Exercise</title>
    <style>
        #box {
            margin-left: auto;
            margin-right: auto;
            width: auto;
            background: red;
            text-align: center;
            font-size: 170px;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <script src="jquery.js"></script>
    <script>
        $(function () {
            fadeout();
        });
        function fadein() {
            $("#box").fadeIn("500", fadeout);
            //UpdateTime();
        }
        function fadeout() {
            UpdateTime();
            $("#box").fadeOut("500", fadein);
        }
        function GetTime() {
            var now = new Date();
            var obj = {
                Hour: now.getHours(),
                Minute: now.getMinutes(),
                Second: now.getSeconds()
            };
            return obj;
        }
        function UpdateTime() {
            var box = $("#box");
            var obj = GetTime();
            if (obj.Hour < 10)
                obj.Hour = "0" + obj.Hour;
            if (obj.Minute < 10)
                obj.Minute = "0" + obj.Minute;
            if (obj.Second < 10)
                obj.Second = "0" + obj.Second;
            box.text(obj.Hour + ":" + obj.Minute + ":" + obj.Second);
        }
    </script>
</body>
</html>

您正在更新淡入完成后,但在淡入完成之前的时间:http://jsfiddle.net/h8kmqsv6/

尝试将对UpdateTime的调用移动到淡入的开头(请参阅http://jsfiddle.net/h8kmqsv6/1/):

function fadein() {
   UpdateTime();
   $("#box").fadeIn("500", fadeout);
}
function fadeout() {
   $("#box").fadeOut("500", fadein);
}

UPDATE:为了改善同步,您可以使用setInterval:

var $box = $("#box");
$box.fadeOut(0);
setInterval(tick, 1000);
function tick() {
    UpdateTime();
    $box.fadeIn(500, function() {
        $box.fadeOut(500);
    });
}

链接:http://jsfiddle.net/h8kmqsv6/6/

UPDATE2:停止tick内部的动画也是一个好主意:

function tick() {
    $box.stop(true, true);
    UpdateTime();
    $box.fadeIn(500, function() {
        $box.fadeOut(500);
    });
}

链接:http://jsfiddle.net/h8kmqsv6/15/