【问题标题】:Javascript CountdownJavascript倒计时
【发布时间】:2016-05-04 07:14:38
【问题描述】:

我已经在网上搜索过,但所有现成的都是您指定日期的地方,它会倒计时到那个日期。我需要的是从“27 分 43 秒”(以那种格式)一直倒计时到 0 的东西,从他们登陆页面时开始,有人有任何可用的 sn-ps 吗?

【问题讨论】:

  • 谷歌搜索“javascript 倒计时分秒”会给你很多选择。

标签: javascript


【解决方案1】:

这样的事情应该可以解决问题。我很无聊,决定自己做而不是谷歌搜索。只需在顶部设置分钟和秒,然后将 onload 中对倒计时的调用更改为您希望它更新的元素的 id。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <script>
    var interval;
    var minutes = 1;
    var seconds = 5;
    window.onload = function() {
        countdown('countdown');
    }

    function countdown(element) {
        interval = setInterval(function() {
            var el = document.getElementById(element);
            if(seconds == 0) {
                if(minutes == 0) {
                    el.innerHTML = "countdown's over!";                    
                    clearInterval(interval);
                    return;
                } else {
                    minutes--;
                    seconds = 60;
                }
            }
            if(minutes > 0) {
                var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
            } else {
                var minute_text = '';
            }
            var second_text = seconds > 1 ? 'seconds' : 'second';
            el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
            seconds--;
        }, 1000);
    }
    </script>
</head>
<body>
<div id='countdown'></div>
</body>
</html>

【讨论】:

  • 赞成,但它应该是 if(seconds == -1) 和 seconds = 59 否则你有,例如,5:01、4:60、4:59...
【解决方案2】:

我做了一个简单的倒计时,你可以使用。

它正在生成格式:

第 X 天、第 X 小时、第 X 分钟、第 X 秒

JS:

countIt();

function countIt(){
    year = 2013;
    month = 05;
    day = 28;
    hours = 12;
    minutes = 00;
    seconds = 00;

    setTimeout(function(){
    endDate = new Date(year, (month - 1), day, hours, minutes, seconds, 00);
    thisDate  = new Date();
    thisDate  = new Date(thisDate.getFullYear(), thisDate.getMonth(), thisDate.getDate(), thisDate.getHours(), thisDate.getMinutes(), thisDate.getSeconds(), 00, 00);

    var daysLeft = parseInt((endDate-thisDate)/86400000);
    var hoursLeft = parseInt((endDate-thisDate)/3600000); 
    var minutsLeft = parseInt((endDate-thisDate)/60000);
    var secondsLeft = parseInt((endDate-thisDate)/1000);

    seconds = minutsLeft*60;
    seconds = secondsLeft-seconds;

    minutes = hoursLeft*60;
    minutes = minutsLeft-minutes;

    hours = daysLeft*24;
    hours = (hoursLeft-hours) < 0 ? 0 : hoursLeft-hours;

    days = daysLeft;

    startCount(days, hours, minutes,seconds);
    }, 1000);
}

function startCount(days, hours, minutes, seconds){
    document.getElementById("counter").innerHTML="DAYS "+days+", HOURS "+hours+", MINUTES "+minutes+", SECONDS: "+seconds;
    countIt();
}

HTML:

<div id="counter"></div>

Click here to see it live

【讨论】:

  • thisDate.getDay() 应该是 thisDate.getDate() ;)
【解决方案3】:

我认为您正在寻找类似this 的东西。

【讨论】:

    【解决方案4】:

    嗯,为什么不直接使用这个:

        <div id="countdown">countdown displayed here</div>
        <script type="text/javascript">                               
            $(document).ready(function() {
                //time to count down
                hoursToGo = 0;
                minutesToGo = 27;
                secondsToGo = 43;
    
                var startTime = new Date();              
                var endTime = new Date();
                endTime.setHours(
                    startTime.getHours() + hoursToGo,
                    startTime.getMinutes() + minutesToGo, 
                    startTime.getSeconds() + secondsToGo, 
                    startTime.getMilliseconds()
                );
    
                //function to update counter
                function update(){
                    var currentTime = new Date();
    
                    var remainingTime = new Date();
                    remainingTime.setTime(endTime.getTime()-currentTime.getTime());
    
                    $("#countdown").text(remainingTime.getHours()+":"+remainingTime.getMinutes()+":"+remainingTime.getSeconds());
    
                    //call itself every second
                    setTimeout(update,1000);
                }
    
                //start the countdown
                update();                
            });
        </script>
    

    编辑 作为一个附加的想法,您可以通过将结束时间作为隐藏表单元素的值传递到下一页来在多个页面上实现这一点。或者至少这就是我要用它做的;-)

    【讨论】:

      【解决方案5】:

      jCounter 是一个插件,它也接受自定义值来显示你想要的任何倒计时

      【讨论】:

        【解决方案6】:

        我还制作了一个倒计时时钟,但使用的是 html5 画布。 如果您喜欢,请随意使用它。 (运行下面的代码片段)

        (function() {
          /**
          * WlCounter pure JS class
          *
          * @class WlCounter
          * @Author: Wiktor Lis
          */
          var WlCounter = function(){
            // date settings - REMEMBER months in Date object are counted as an Array from 0! So months range is between 0 to 11. Other than that everything is just as you would expect it to be.
            this.setEventDate(new Date(2017, 03, 22, 22, 5, 0), 'Curently Unused'); // NOTE! months are represented from 0 to 11 in Date objects
            this.setEventEndDate(new Date(2019, 04, 03, 22, 9, 0), 'Curently Unused', 'Curently Unused'); // NOTE! months are represented from 0 to 11 in Date objects
            
            // CLOCK SETTINGS
            // clock size
            this.container = {
              x: 0,
              y: 0,
              w: 150,
              h: 150
            };
            // ring stroke
            this.stroke = this.container.w / 10;
            // number font size
            this.numFontSize = this.container.w / 6 +'px';
            // label font size
            this.labelFontSize = this.container.w / 10 +'px';
            // colors
            this.colorRing = "hsla(355, 0%, 90%, 1)";
            this.colorActive = "hsla(355, 100%, 50%, 1)";
            this.colorTimedOut = "hsla(355, 0%, 50%, 0.3)";
            
            // OTHER
            // init objets
            this.curent = {};
            this.counter = {};
          }
        
          /**
          * This method creates canvas based on css id 
          *
          * @method createCanvas
          * @param {String} cssId of canvas DOM object
          */
          WlCounter.prototype.createCanvas = function(cssId){
            this.canvas = document.getElementById(cssId);
            this.canvas.setAttribute("width", this.container.w);
            this.canvas.setAttribute("height", this.container.h);
            this.c = this.canvas.getContext('2d');
            return this.c
          }
        
          /**
          * Init all canvas objects and start counting down
          *
          * @method init
          */  
          WlCounter.prototype.init = function(){
            this.daysBox = this.createCanvas('canvas-d');
            this.hoursBox = this.createCanvas('canvas-h');
            this.minutesBox = this.createCanvas('canvas-m');
            this.secoundsBox = this.createCanvas('canvas-s');
            this.msBox = this.createCanvas('canvas-ms');
            this.startCounting();
            this.intervalClock();
          }
        
          /**
          * Assign curent time to class properities
          *
          * @method getTime
          */
          WlCounter.prototype.getTime = function() {
            this.curent.time = new Date();
            this.curent.days = this.curent.time.getDay();
            this.curent.hours = this.curent.time.getHours();
            this.curent.minutes = this.curent.time.getMinutes();
            this.curent.seconds = this.curent.time.getSeconds();
            this.curent.milliseconds = this.curent.time.getMilliseconds();
          }
        
          /**
          * Creates event start date  // and its message
          *
          * @method setEventDate
          * @param {Object Date} date - defines event start date
          * @param {String} messageBefore - curently unused
          */
          WlCounter.prototype.setEventDate = function(date, messageBefore) {
            this.eventStarts = date;
            this.messageBefore = messageBefore;
          }
        
          /**
          * Define event end date
          *
          * @method setEventEndDate
          * @param {Object Date} date 
          * @param {String} messageDuring 
          * @param {String} messageAfter
          */
          WlCounter.prototype.setEventEndDate = function(date, messageDuring, messageAfter) {
            this.eventEnds = date;
            this.messageDuring = messageDuring;
            this.messageAfter = messageAfter;
          }
        
          /**
          * Substract curent time from event date and define how many of days, hours, min, s, ms are left
          * If event starts counter finished -> change counter color to greenish (hsla(160, 100%, 38%, 1)) and count to events End time.
          *
          * @method startCounting
          */
          WlCounter.prototype.startCounting = function() {
            this.intervalToEvent = setInterval(function() {
              this.getTime();
              if (this.curent.time < this.eventStarts) {
                this.subject = this.eventStarts;
              } else if(this.curent.time < this.eventEnds) {
                // change colors
                this.colorActive = "hsla(160, 100%, 38%, 1)";
                this.subject = this.eventEnds;
              } else {
                this.stagnate();
                return;
              }
              
              var until = this.subject - this.curent.time;
              this.counter.ms = Math.floor(until % 1000);
              this.counter.sec = Math.floor(until / (1000) % 60);
              this.counter.min = Math.floor(until / (1000 * 60) % 60);
              this.counter.hours = Math.floor(until / (1000 * 60 * 60 ) % 24);
              this.counter.days = Math.floor(until / (1000 * 60 * 60 * 24));
              // console.log(this.counter);
              
            }.bind(this), 16.666);
          }
        
          /**
          * If counter will go pass the event start and end date, simply stagneta the clock assigning 0 to each clock
          *
          * @method stagnate
          */
          WlCounter.prototype.stagnate = function() {
              clearInterval(this.intervalToEvent);
              this.counter.ms = 0;
              this.counter.sec = 0;
              this.counter.min = 0;
              this.counter.hours = 0;
              this.counter.days = 0;
          }
        
          /**
          * Convert deg to radians
          *
          * @method degToRad
          * @param {Integer} deg
          */
          WlCounter.prototype.degToRad = function(deg) {
            radians = Math.PI / 180;
            return radians * deg;
          }
          
          /**
          * Draw the clock and sign it with the text from the @param2
          *
          * @method drawClock
          * @param {Object} ctx - canvas selection
          * @param {Array} timeUnit - example [this.counter.days, 365, 'D'] -> [0] counter number of days -> [1] max days for the clock to count down -> [2] Title that will be assign to the clock under the number
          */
          WlCounter.prototype.drawClock = function(ctx, timeUnit) {
              // background - gradient
              gradient = ctx.createRadialGradient(this.container.w/2, this.container.h/2, 55, this.container.w/2, this.container.h/2,  this.container.w/2);
              gradient.addColorStop(1, 'rgba(245,245,245, 0.1)');
              gradient.addColorStop(0, 'white');    
            
              // canvas rect
              // ctx.fillStyle = "white";
              ctx.fillStyle = gradient;
              ctx.fillRect(0,0,this.container.w, this.container.h);
            
              // clock rim
              ctx.beginPath();
              ctx.strokeStyle = this.colorRing;
              ctx.lineWidth = this.container.w / 18;
              ctx.arc(this.container.w/2, this.container.h/2,this.container.h/2-this.stroke, this.degToRad(270), this.degToRad(0 - 90));
              ctx.stroke();
            
              // clock time
              ctx.beginPath();
              // ctx.shadowBlur = this.stroke-10;
              // ctx.shadowColor = "hsla(355, 100%, 0%, 0.2)";
              // ring countdown
              // ctx.lineCap = "round";
              ctx.strokeStyle = this.colorActive;
              if(timeUnit[0] == 0) ctx.shadowColor = ctx.strokeStyle = this.colorTimedOut;  // if time is 0 set color to gray
              ctx.lineWidth = this.stroke;
              // draw ring countdown
              ctx.arc(this.container.w/2, this.container.h/2,this.container.h/2-this.stroke, this.degToRad(270), this.degToRad(360 * timeUnit[0] / timeUnit[1] - 90));
            
              // text - number
              ctx.font = this.numFontSize+" Arial";
              ctx.textAlign = 'center';
              ctx.textBaseline = 'middle';
              ctx.fillStyle = this.colorActive;
              if(timeUnit[0] == 0) ctx.fillStyle = this.colorTimedOut;
              if(timeUnit[1] == 60000) timeUnit[0] = Math.round(timeUnit[0]/1000);
              ctx.fillText(timeUnit[0],this.container.w/2,this.container.h/2);
            
              // text - label
              ctx.font = this.labelFontSize+" Arial";
              ctx.textAlign = 'center';
              ctx.textBaseline = 'middle';
              ctx.fillText(timeUnit[2],this.container.w/2,this.container.h/2 + (this.container.w / 5));
              
              // draw!
              ctx.stroke();
          }
        
          /**
          * Set interval to draw clock around 60 frames per seckound (1s / 60  = 16.666)
          *
          * @method intervalClock
          */
          WlCounter.prototype.intervalClock = function() {
            var interval = setInterval(function(){
              // cl(this.counter.ms);
              this.drawClock(this.daysBox, [this.counter.days, 365, 'D']);
              this.drawClock(this.hoursBox, [this.counter.hours, 24, 'H']);
              this.drawClock(this.minutesBox, [this.counter.min, 60, 'M']);
              this.drawClock(this.secoundsBox, [this.counter.sec, 60, 'S']);
              this.drawClock(this.msBox, [this.counter.ms, 1000, 'ms']);
            }.bind(this), 16.666);
          }
          
          /* RUN WlCounter */
          var counter = new WlCounter();
          
          // FUTURE -> To Do
          // set event start and end
          // counter.setEventStart(foo);
          // counter.setEventEnd(foo);
          // counter.onEventStart(function(){
            // ...
          // });
          // counter.onEventEnd(function({
            // ...
          // });
          counter.init();
        })();
        * {
          padding: 0px;
          margin: 0px;
          text-decoration: none;
          border: none;
        }
        
        html, body {
          position: relative;
          padding-top: 20px;
          margin: 0 auto;
        }
        
        #wrap, .text {
          width: 770px;
          margin: auto;
        }
        
        canvas {
          box-sizing: border-box;
          border-bottom: 5px solid gray;
          height: 100%;
        }
        
        h1, p {
          font-weight: 400;
          color: #666;
          font-size: 2.5em;
          width: 100%;
          text-align: center;
        }
        
        p {
          font-size: 1em;
          text-align: left;
        }
        
        ul ol {
          padding-left: 20px;
          list-style-type: decimal;
          line-height: 2em;
        }
        <div class="text">
          <h1>"WlCounter" pure JS class</h1>
        </div>
        <div id="wrap">
          <canvas id="canvas-d"></canvas>
          <canvas id="canvas-h"></canvas>
          <canvas id="canvas-m"></canvas>
          <canvas id="canvas-s"></canvas>
          <canvas id="canvas-ms"></canvas>
        </div>
        <div class="text">
          <p>JS WlCounter class counts-down to the event starting and ending date with color change on reaching the first one. After event start date is reached it changes the color to green and start count-down to events end date (if end date was specyfied and is more then curent time). So when event is ended, counter gets graied out and set 0</p>
        </div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-05-08
          • 1970-01-01
          • 1970-01-01
          • 2019-02-17
          • 2013-03-17
          • 2011-12-08
          • 2011-06-14
          相关资源
          最近更新 更多