1.给定一个时间,然后写出它和当前时间的倒计时(从毫秒开始转换)
<p id="app">
00:00:00;
</p>
<script>
function handleTime(value) {
if (value < 10) {
return "0" + value;
}
return "" + value;
}
function showTime() {
var app = document.getElementById("app");
var endTime = "2020-12-01 23:50:00";
//1.获取结束时间的毫秒
endTime = new Date(endTime).getTime();
//2.获取当前时间的毫秒
var nowTime = new Date().getTime();
//3.获取他们之间的差
var gapTime = endTime - nowTime;
console.log(gapTime);
//4.毫秒和时分秒的转换
var s = Math.floor(gapTime / 1000);
var houer = handleTime(Math.floor(s / 3600));
s = Math.floor(s % 3600);
var minute = handleTime(Math.floor(s / 60));
second = handleTime(Math.floor(s % 60));
console.log(houer);
console.log(minute);
console.log(second);
var sum = houer + ":" + minute + ":" + second;
console.log(sum);
app.innerHTML=sum;
// setTimeout(function(){
// showTime()
// },1000)
}
//showTime();
showTime();
setInterval(function(){
showTime();
},1000)
</script> //函数的两种写法
2.动态时钟
<div>
<img src="./images/0.png" alt="">
<img src="images/0.png" alt="">
<span>:</span>
<img src="images/0.png" alt="">
<img src="images/0.png" alt="">
<span>:</span>
<img src="images/0.png" alt="">
<img src="images/0.png" alt="">
</div>
<script>
function handleTime(value) {
if (value < 10) {
return "0" + value;
}
return "" + value;
}
function showTime() {
var d = new Date();
var hour = handleTime(d.getHours());
var minute = handleTime(d.getMinutes());
var second = handleTime(d.getSeconds());
var imgs = document.querySelectorAll("img");
var arr = hour + minute + second;
// console.log(arr);
//将图片的地址设置为动态
for (i = 0; i < imgs.length; i++) {
imgs[i] .src= "images/" + arr[i] + ".png"
//imgs[i].src=`images/`${sum[i]}.png`;
}
setTimeout(function(){
showTime()
},1000)
}
showTime();
</script>