DIV CSS 佈局教程網

JavaScript 節日倒計時器實作
編輯:關於JavaScript     

本範例以 JavaScript 打造一個可重複使用的節日倒計時器,透過 cdtime 建構函式封裝倒數邏輯,並以自訂的格式化函式決定顯示樣式。範例中同時展示英文的「days / hours / minutes / seconds」格式,以及中文的「天 / 時 / 分 / 秒」格式,還能自動推算到下一年的聖誕節。

在線預覽:https:///keleyi/phtml/jstexiao/17.htm

以下是程式碼:


<!DOCTYPE html>
<html>
<head>
<title>javascript節日倒計時</title>
<style type="text/css">
.keleyilcd { background-color: black; color: yellow; font: bold 18px MS Sans Serif; padding: 3px; }
.keleyilcd sup { font-size: 80%; }
</style>
<script type="text/javascript">
function cdtime(container, targetdate) {
if (!document.getElementById || !document.getElementById(container)) return
this.container = document.getElementById(container)
this.currentTime = new Date()
this.targetdate = new Date(targetdate)
this.timesup = false
this.updateTime()
}
cdtime.prototype.updateTime = function () {
var thisobj = this
this.currentTime.setSeconds(this.currentTime.getSeconds() + 1)
setTimeout(function () { thisobj.updateTime() }, 1000)
}
cdtime.prototype.displaycountdown = function (baseunit, functionref) {
this.baseunit = baseunit
this.formatresults = functionref
this.showresults()
}
cdtime.prototype.showresults = function () {
var thisobj = this
var timediff = (this.targetdate - this.currentTime) / 1000
if (timediff < 0) { this.timesup = true; this.container.innerHTML = this.formatresults(); return; }
var oneMinute = 60, oneHour = 60 * 60, oneDay = 60 * 60 * 24
var dayfield = Math.floor(timediff / oneDay)
var hourfield = Math.floor((timediff - dayfield * oneDay) / oneHour)
var minutefield = Math.floor((timediff - dayfield * oneDay - hourfield * oneHour) / oneMinute)
var secondfield = Math.floor((timediff - dayfield * oneDay - hourfield * oneHour - minutefield * oneMinute))
this.container.innerHTML = this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function () { thisobj.showresults() }, 1000)
}
function formatresults2() {
if (this.timesup == false) {
var displaystring = " 到聖誕節還有<span class='keleyilcd'>" + arguments[0] + " <sup>天</sup> " + arguments[1] + " <sup>時</sup> " + arguments[2] + " <sup>分</sup> " + arguments[3] + " <sup>秒</sup></span>"
} else { var displaystring = ""; }
return displaystring
}
</script>
</head>
<body>
<div id="countdowncontainer2"></div>
<script type="text/javascript">
var currentyear=new Date().getFullYear()
var thischristmasyear=(new Date().getMonth()>=11 && new Date().getDate()>25)? currentyear+1 : currentyear
var christmas=new cdtime("countdowncontainer2", "December 25, "+thischristmasyear+" 0:0:00")
christmas.displaycountdown("days", formatresults2)
</script>
</body>
</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved