JS简单实现倒计时功能

效果图:

如图所示,倒计时还有 24时 00分 25秒

代码思路:

主要是使用了定时器 setInterval,每隔一秒去计算 当前时间 距离 设定时间 所间隔的毫秒数,然后将得到的间隔毫秒转换为 时分秒 等单位,最后渲染到页面上。

本案例适用范围:

本案例显示的是距离当前时间的 时分秒,如果需要返回 天时分秒 、月天时分秒 等,则需要修改把毫秒数转换单位算法的写法。

实现代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            display: inline-block;
            width: 40px;
            height: 40px;
            margin: 10px;
            background-color: black;
            color: white;
            line-height: 40px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div>1</div>时
    <div>2</div>分
    <div>3</div>秒
    <script>
        var divs = document.querySelectorAll('div');
        var inputTime = +new Date(prompt('请以 xxxx-xx-xx xx:xx:xx 的格式输入一个未来的时间:'));

        function fn() {
            var nowTime = +new Date();
            if ((inputTime - nowTime) >= 0) { //判断距离输入时间的间隔是否为正数,如果非正数则设置间隔为0
                var times = (inputTime - nowTime) / 1000;
            } else {
                times = 0;
            }
            var h = parseInt(times / 60 / 60);
            divs[0].innerHTML = h < 10 ? '0' + h : h;
            var m = parseInt(times / 60 % 60);
            divs[1].innerHTML = m < 10 ? '0' + m : m;
            var s = parseInt(times % 60);
            divs[2].innerHTML = s < 10 ? '0' + s : s;
        }
        fn(); //先执行一次,这样在刷新页面的时候能够立刻有数据而非等待1s后才有数据
        setInterval(fn, 1000); //定时任务
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_42207975/article/details/106520172