子钦加油

扩大
缩小

根据后端传的时间前端js进行倒计时

一、故事背景:

1. 今天公司有个项目需求
2. 在前端页面实现一个倒计时功能
3. 初步设想:后端根据需求规定一个未来的时间,前端根据当前时间进行计算
4. 然后将时间格式化,时分秒的格式
5. 时间倒计时完成,刷新页面获取最新的页面
6. 最后在前端展示;大致是这样
二、上代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="js_time_txt">
</div>

<script src="./jquery-3.3.1.min.js"></script>
<script>
    $(function () {
// 倒计时
        var _ordertimer = null;
        var data = new Date();
        var txt = $('.js_time_txt');
        var buyTime = '2018-09-20 22:25:59'; //开抢时间
        var nowTime = '2018-09-20 22:23:45'; //接口返回当前时间
        var dateDiff = new Date(nowTime) - new Date(getnow()); //请求时间戳与本地时间戳
        if (dateDiff < 0) {
            dateDiff = Math.abs(dateDiff);
        }

        if (new Date(nowTime) > new Date(buyTime)) {
            $('.time-range').hide(); //已开枪
            return;
        } else {
            leftTimer(buyTime);
            _ordertimer = setInterval(function () {
                leftTimer(buyTime)
            }, 1000);
        }

        // 获取当前时间 xxxx/xx/xx 00:00:00
        function getnow() {
            var year = data.getFullYear();
            var month = parseInt(data.getMonth() + 1) >= 10 ? parseInt(data.getMonth() + 1) : '0' + parseInt(data.getMonth() + 1);
            var day = data.getDate();
            var hours = data.getHours();
            var minutes = data.getMinutes();
            var seconds = data.getSeconds();
            var now = year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds;
            return now;
        }

        function leftTimer(enddate) {

            var leftTime = (new Date(enddate)) - new Date + dateDiff;

            var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
            var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时
            var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟
            var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数
            days = checkTime(days);
            hours = checkTime(hours);
            minutes = checkTime(minutes);
            seconds = checkTime(seconds);

            if (days >= 0 || hours >= 0 || minutes >= 0 || seconds >= 0)
                txt.html(days + "天" + hours + "小时" + minutes + "分" + seconds + "秒");
            if (days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0) {
                window.clearInterval(_ordertimer);
                _ordertimer = null;
            }
        }

        function checkTime(i) { //将0-9的数字前面加上0,例1变为01
            if (i < 10) {
                i = "0" + i;
            }
            return i;
        }
    })
</script>
</body>
</html>

  

posted on 2020-01-29 12:52  子钦加油  阅读(...)  评论(...编辑  收藏

导航

返回顶部