1.处理时间
<p id="app">10:10:10 </p>
<script>
function handleTime(value){
if(value<10){
return "0"+value
}else{
return ""+value
}
}
function showTime(){
var app = document.getElementById("app")
var endTime = "2020-12-01 16:50:00"
/* 1.获取结束时间的毫秒 */
endTime = new Date(endTime).getTime()
/* 2.获取当前时间的毫秒 */
var nowTime = new Date().getTime()
/* 3.获取他们之间的差 */
var gapTime = endTime-nowTime
/* 4.将他们的差转化为时分秒 */
var seconds = Math.floor(gapTime/1000);
var hours = handleTime(Math.floor(seconds/3600));
seconds = seconds%3600;
var minutes = handleTime(Math.floor(seconds/60));
seconds = handleTime(seconds%60);//不需要向下取整
var sum = hours+":"+minutes+":"+seconds;
app.innerHTML = sum
/* 超时调用
setTimeout(fucntion(){
showTime()
},1000)
*/
}
showTime();
/* 间歇调用 */
setInterval(function(){
showTime()
},1000)
</script>
2.动态时钟
<div id="box">
<img src="images/0.png" alt="">
<img src="images/0.png" alt="">
<span class="colon">:</span>
<img src="images/0.png" alt="">
<img src="images/0.png" alt="">
<span class="colon">:</span>
<img src="images/0.png" alt="">
<img src="images/0.png" alt="">
</div>
function handleTime(value){
if(value<10){
return "0"+value
}else{
return ""+value
}
}
function showTime(){
var imgs = document.querySelectorAll("#box img")
var d = new Date()
var hours = handleTime(d.getHours())
var minutes = handleTime(d.getMinutes())
var seconds = handleTime(d.getSeconds())
var sum = hours+minutes+seconds;
// console.log(sum);
// console.log(typeof sum);
for(var i=0;i<imgs.length;i++){
//imgs[i].src = "images/"+sum[i]+".png"
// 字符串模板:可以在字符串中使用变量 ${}
imgs[i].src = `images/${sum[i]}.png`
}
setTimeout(function(){//最好写超时调用
showTime()
},1000)
}
showTime()