美文网首页
Javascript倒计时效果

Javascript倒计时效果

作者: visitor009 | 来源:发表于2018-11-02 17:36 被阅读0次

    相对于服务器的时间,天 时 分 秒

     // 倒计时
    //param{Date}start 开始日期 2018-11-03 06:00:00
    //param{Date}end 结束日期 2018-11-03 06:00:00
    function countTime(start,end) {
      // 开始时间
      var date = new Date(start.replace(/-/g,'/')); // ios 不支持2018-11-03 06:00:00
      var now = date.getTime();
      //设置截止时间
      var endDate = new Date(end.replace(/-/g,'/'));
      var end = endDate.getTime();
      //时间差
      var leftTime = 0;
      var timer = null;
    
      var d=00,h=00, m = 00, s=00;
      count();
      function count() {
        now += 1000;
        leftTime = end - now;
        if (leftTime >= 0) {
            d = Math.floor(leftTime/1000/60/60/24);  
            h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
            m = Math.floor(leftTime / 1000 / 60 % 60);
            s = Math.floor(leftTime / 1000 % 60);
            if (h < 10 ) {
              h = '0'+h;
            }
            if (m < 10 ) {
              m = '0'+m;
            }
            if (s < 10 ) {
              s = '0'+s;
            }
        } else {
          h = 00;
          m = 00;
          s = 00;
          clearTimeout(timer);
        }
        document.getElementById("h").innerHTML = h;
        document.getElementById("m").innerHTML = m;
        document.getElementById("s").innerHTML = s;
        timer = setTimeout(function () {
            count();
        }, 1000);
      }
    
    
    }
    countTime("2018-11-03 06:00:00","2018-11-04 06:00:00");
    

    相对于本地的时间,天 时 分 秒

    // 倒计时
    //param{Date}end 结束日期 2018-11-03 06:00:00
    function countTime(end) {
      // 开始时间
      var date = new Date();
      var now = date.getTime();
      //设置截止时间
      var endDate = new Date(end.replace(/-/g,'/'));
      var end = endDate.getTime();
      //时间差
      var leftTime = 0;
      var timer = null;
    
      var h=00, m = 00, s=00;
      count();
      function count() {
        date = new Date());
        now = date.getTime();
        leftTime = end - now;
        if (leftTime >= 0) {
            h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
            m = Math.floor(leftTime / 1000 / 60 % 60);
            s = Math.floor(leftTime / 1000 % 60);
            if (h < 10 ) {
              h = '0'+h;
            }
            if (m < 10 ) {
              m = '0'+m;
            }
            if (s < 10 ) {
              s = '0'+s;
            }
        } else {
          h = 00;
          m = 00;
          s = 00;
          clearTimeout(timer);
        }
        document.getElementById("h").innerHTML = h;
        document.getElementById("m").innerHTML = m;
        document.getElementById("s").innerHTML = s;
        timer = setTimeout(function () {
            count();
        }, 1000);
      }
    
    
    }
    countTime("2018-11-04 06:00:00");
    

    相关文章

      网友评论

          本文标题:Javascript倒计时效果

          本文链接:https://www.haomeiwen.com/subject/lmvcxqtx.html