1、实现一个距离0点的倒计时,主要是通过获取当下时间戳转时、分、秒,然后再24-时就行
2、实现的代码
```<template>
<div class="countDown">
距离0点倒计时:
<span>0</span>
<span>天</span>
<span>{{h}}</span>
<span>时</span>
<span>{{m}}</span>
<span>分</span>
<span>{{s}}</span>
<span>秒</span>
<div>当前时间:{{now}}</div>
</div>
</template>
<script>
export default {
name: "APP",
data() {
return {
h: "",
m: "",
s: "",
now: new Date().toLocaleTimeString()
};
},
methods: {
countdown() {
let now = new Date(); // 获取当前时间
let hour = now.getHours(); // 时
let min = now.getMinutes(); // 分
let sec = now.getSeconds(); // 秒
this.h = 24 - hour; // 倒计时 时
if (min > 0 || sec > 0) {
this.h -= 1;
}
this.m = 60 - min; // 倒计时 分
if (sec > 0) {
this.m -= 1;
}
if (this.m == 60) {
this.m = 0;
}
this.s = 60 - sec; // 倒计时 秒
if (this.s == 60) {
this.s = 0;
}
this.h = this.h.toString();
this.m = this.m.toString();
this.s = this.s.toString();
if (this.h.length == 1) {
this.h = "0" + this.h;
}
if (this.m.length == 1) {
this.m = "0" + this.m;
}
if (this.s.length == 1) this.s = "0" + this.s;
},
startCountdown() {
setInterval(() => {
this.countdown();
this.now = new Date().toLocaleTimeString();
}, 1000);
}
},
created() {
this.startCountdown();
}
};
</script>
<style scoped>
.countDown {
color: black;
}
span {
width: 40px;
height: 20px;
font-size: 14px;
padding: 0, 2px;
}
span:nth-child(2n-1) {
background-color: orange;
color: white;
}
</style>
3.效果图: