想用JavaScript做一个时钟Clock Web App,请问如何处理添加多个Clock? 每个Clock是一个div,用JS控制添加和删除,这样的思路对吗?
想尝试用PhoneGap生成ios, Android 平台的app, 上面的思路还能用吗,代码上还要做特别的修改吗?
這裡實現了一個簡單的 Clock
jsFiddle
class Clock {
constructor(appendTo)
// 建立一個 div
this.el = document.createElement('div')
// 設定 class 為 clock
this.el.className = 'clock'
// 插入元素
appendTo.appendChild(this.el)
// 初始化 timer
this.timer = null
}
start() {
// 500ms 檢查一次時間,並改變內容
this.timer = setInterval(() => {
const now = new Date()
const h = now.getHours()
const m = now.getMinutes()
const s = now.getSeconds()
this.el.textContent = `${h}:${m}:${s}`
}, 500)
return this
}
// 停止
stop() {
clearInterval(this.timer)
}
// 刪除
destroy() {
this.stop()
this.el.remove()
}
}
// 插入一個 Clock 到 document ,或是可以指定其他 Dom
new Clock(document.documentElement).start()
至於 PhoneGap
雖然我不太熟悉,但是就這些代碼來講,應該是不用做特別修改就可以在各平台運行了。