限時特 prices 的倒數計時是電商頁面的常見元素。以下把計時邏輯封裝成一個 jQuery 外掛,只要傳入結束時間就能用。
/**
* Author: Black_Jay郗
* downCount: 時間轉換 倒計時
*/
(function ($) {
$.fn.downCount = function (options, callback) {
var settings = $.extend({
date: null,
offset: null
}, options);
if (!settings.date) {
$.error('Date is not defined.');
}
if (!Date.parse(settings.date)) {
$.error('Incorrect date format, it should look like this, 12/24/2012 12:00:00.');
}
var container = this;
var currentDate = function () {
var date = new Date();
/*var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
var new_date = new Date(utc + (3600000*settings.offset));*/
return date;
};
function countdown () {
var target_date = new Date(settings.date),
current_date = currentDate();
var difference = target_date - current_date;
if (difference < 0) {
clearInterval(interval);//取消 setInterval() 函數設定的定時執行操作
if (callback && typeof callback === 'function') callback();
return;
}
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
var days = Math.floor(difference / _day),
hours = Math.floor(((difference % _day) / _hour) + (days*24)),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
container.find('.hours').text(hours);
container.find('.minutes').text(minutes);
container.find('.seconds').text(seconds);
};
var interval = setInterval(countdown, 1000);
};
})(jQuery);
<!-- 倒計時顯示Star --> <p class="countdown"> <span class="hours">00</span>: <span class="minutes">00</span>: <span class="seconds">00</span> </p> <!-- 倒計時End -->
$('.countdown').downCount({
date: '11/09/2016 13:45:00',
offset: +10
}, function () {
alert('秒殺已結束');
});
$.extend 合併預設設定,讓 date 與 offset 都可省略,並在缺少參數或日期格式錯誤時透過 $.error 拋出提示。Math.floor 配合取餘運算逐段拆出天、時、分、秒。clearInterval 停掉計時器,再執行傳入的 callback,可在此處觸發「已結束」的提示或切換版面狀態。把這段外掛掛到頁面上,限時活動的倒數顯示就完成了。