倒计时小时和分钟

Countdown hours and minutes

本文关键字:分钟 小时 倒计时      更新时间:2023-09-26

我有一个今天的时间值。我需要一个倒计时,显示到那时还有多少小时和分钟。当用户在页面上时,我需要这个倒计时来更新分钟数。

我做了一个快速搜索,看到了很多插件,但我认为如果没有额外的脚本,这可能会很简单。

Time left <span class="remainingTime"></span>
var day = new Date(),
    now = d.getHours() + ":" + d.getMinutes(),
    end = '23:00';

我想我需要某种转换,也许到毫秒来获得显示的初始时间,然后可能设置Timeout并递减60000?

这个怎么样?小巧简洁。

function SetTimer(hours, minutes){
    var end = new Date();
    end.setHours(hours);
    end.setMinutes(minutes);
    var secondsLeft = (end - new Date()) / 60000;
    var hoursLeft = Math.floor(secondsLeft / 60);
    var minutesLeft = Math.round(secondsLeft % 60);
    
    $('.remainingTime').text(hoursLeft + ' : ' + minutesLeft);
}
SetTimer(23, 59);
setInterval(function(){
    SetTimer(23, 59);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Time left <span class="remainingTime"></span>

有一百万个谷歌结果显示Javascript小时/分钟倒计时脚本。我在10秒内找到了这个脚本,并在30秒内完成了它。在下次提问之前,你真的应该做更多的研究。以下是第一个结果之一的脚本:

function DaysHMSCounter(initDate, id){
    this.counterDate = new Date(initDate);
    this.container = document.getElementById(id);
    this.update();
}
DaysHMSCounter.prototype.calculateUnit=function(secDiff, unitSeconds){
    var tmp = Math.abs((tmp = secDiff/unitSeconds)) < 1? 0 : tmp;
    return Math.abs(tmp < 0 ? Math.ceil(tmp) : Math.floor(tmp));
}
DaysHMSCounter.prototype.calculate=function(){
    var secDiff = Math.abs(Math.round(((new Date()) - this.counterDate)/1000));
    this.days = this.calculateUnit(secDiff,86400);
    this.hours = this.calculateUnit((secDiff-(this.days*86400)),3600);
    this.mins = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)),60);
    this.secs = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)-(this.mins*60)),1);
}
DaysHMSCounter.prototype.update=function(){ 
    this.calculate();
    this.container.innerHTML =
        " <strong>" + this.days + "</strong> " + (this.days == 1? "day" : "days") +
        " <strong>" + this.hours + "</strong> " + (this.hours == 1? "hour" : "hours") +
        " <strong>" + this.mins + "</strong> " + (this.mins == 1? "min" : "mins") +
        " <strong>" + this.secs + "</strong> " + (this.secs == 1? "sec" : "secs");
    var self = this;
    setTimeout(function(){self.update();}, (1000));
}

这样使用:

<div id="myCounter"></div>
<script>
new DaysHMSCounter('December 25, 2015 00:00:00', 'myCounter');
</script>

试用演示

我相信你可以修改它以删除"天"answers"秒"部分。