jq中动态加DOM后进行循环倒计时

<!DOCTYPE html>
<html lang="zh-cn">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>循环倒计时</title>

</head>

<body>
  <div id="app">
  </div>

  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script>
    $(function () {
      /*倒计时*/ //秒 位置  回调函数
      function newCountdown(s, $_, cb) {
        //秒=(时间戳)/1000
        s = parseInt(s)
        var this_time_countdown;
        var timer = setInterval(function () {
          if (!$_.length) {
            return clearInterval(timer);  //无dom时自动清除定时器
          };
          s--;
          //天
          var day = Math.floor(s / 24 / 3600)
          //时
          var hour = Math.floor((s - day * (24 * 3600)) / 3600)
          //分
          var minute = Math.floor((s - day * (24 * 3600) - hour * 3600) / 60)
          //秒
          var second = Math.floor(s - day * (24 * 3600) - hour * 3600 - minute * 60)
          if (day > 0) {
            this_time_countdown = day + "天" + hour + "时" + minute + "分" + second + "秒"
          } else {
            if (hour > 0) {
              this_time_countdown = hour + "时" + minute + "分" + second + "秒"
            } else {
              if (minute > 0) {
                this_time_countdown = minute + "分" + second + "秒"
              } else {
                this_time_countdown = second + "秒"
              }
            }
          };
          $_.text(this_time_countdown);
          if (s == 0) {
            clearInterval(timer);
            if (cb && typeof (cb) === 'function') {
              cb();
            };
          }
        }, 1000);
      };

      //加入DOM
      var timeNum = 3;	//倒计时时间
      var dom = '<p>倒计时:<span id="timeTipBox">' + (timeNum-1) + '秒</span></p>';
      $(dom).appendTo('body');
      //倒计时--start
      function setTime() {
        newCountdown(timeNum, $('#timeTipBox'), function () {
          setTime();
        });
      }
      //启动倒计时,防止dom没有渲染
      setTimeout(() => {
        setTime();
      }, 0);
    });
  </script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值