【发布时间】:2020-01-10 13:26:08
【问题描述】:
我对 Jquery 倒数计时器有疑问。脚本每天倒计时到同一时间。 倒计时时间不对,倒计时一小时。任何想法如何解决这一问题?它托管在 JSFiddle 上。
(function($){
var date = new Date(),
month = date.getMonth();
day = date.getDate(),
weekDay = date.getDay(),
hours = {
start: new Date(date.getFullYear(), month, day),
end: new Date(date.getFullYear(), month, day)
};
// weekDay var [0 = sun, 1 = mon, 2 = tues ... 5 = fri 6 = sat]
// If it's Monday - Friday
if(weekDay >= 1 && weekDay <= 5){
// Start at 7am, end at 8pm
hours.start.setHours(7);
hours.end.setHours(22);
// If it's Saturday
} else if(weekDay == 6){
// Start at 8am, end at 8pm
hours.start.setHours(8);
hours.end.setHours(20);
// If it's Sunday
} else {
// Start at 9am, end at 6pm
hours.start.setHours(9);
hours.end.setHours(18);
}
function countDown(){
var date = new Date(),
countHours = ('0' + (hours.end.getHours() - date.getHours())).substr(-2),
countMinutes = ('0' + (59 - date.getMinutes())).substr(-2),
countSeconds = ('0' + (59 - date.getSeconds())).substr(-2);
// If it's currently not within the hours, don't show the countdown
if(date.getHours() < hours.start.getHours() || date.getHours() > hours.end.getHours()){
$('.countdown').hide();
} else if($('.countdown').not(':visible')){
$('.countdown').show();
}
$('.countdown .hours').text(countHours);
$('.countdown .minutes').text(countMinutes);
$('.countdown .seconds').html(countSeconds);
}
$(function(){
setInterval(function(){
countDown();
}, 1000);
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="countdown">
<span class="hours"></span>H <span class="minutes"></span>M <span class="seconds"></span>S
</div>
【问题讨论】:
-
在计算小时数时,您没有考虑 分钟。分钟和秒也会发生同样的事情。
标签: javascript jquery countdown