基于vue实现倒计时功能 天 /时/分/秒 / / 时/分秒
其实很简单,这里就直接上代码了,都写好注释了天/时/分/秒//倒计时countTime: function() {// 定义结束时间戳const end = Date.parse(new Date('2020-1-12 10:10:10'))// 定义当前时间戳const now = Date.parse(new Date()...
·
其实很简单,这里就直接上代码了,都写好注释了
天/时/分/秒
//倒计时
countTime: function() {
// 定义结束时间戳
const end = Date.parse(new Date('2020-1-12 10:10:10'))
// 定义当前时间戳
const now = Date.parse(new Date())
// 做判断当倒计时结束时都为0
if (now >= end) {
this.d = 0
this.h = 0
this.m = 0
this.s = 0
return
}
// 用结束时间减去当前时间获得倒计时时间戳
const msec = end - now
let d = parseInt(msec / 1000 / 60 / 60 / 24) //算出天数
let h = parseInt(msec / 1000 / 60 / 60 % 24)//算出小时数
let m = parseInt(msec / 1000 / 60 % 60)//算出分钟数
let s = parseInt(msec / 1000 % 60)//算出秒数
//给数据赋值
this.d = d
this.h = h > 9 ? h : '0' + h
this.m = m > 9 ? m : '0' + m
this.s = s > 9 ? s : '0' + s
//定义this指向
const that = this
// 使用定时器 然后使用递归 让每一次函数能调用自己达到倒计时效果
setTimeout(function () {
that.countTime()
}, 1000)
}
时/分/秒
// 倒计时
countTime: function () {
// 获取当前时间
var date = new Date();
var now = date.getTime();
//设置截止时间
var endDate = new Date("2020-1-22 23:23:23");
var end = endDate.getTime();
//时间差
var leftTime = end - now;
//定义变量 d,h,m,s保存倒计时的时间
if (leftTime >= 0) {
this.d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
this.h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
this.m = Math.floor(leftTime / 1000 / 60 % 60);
this.s = Math.floor(leftTime / 1000 % 60);
this.sum_h = this.d * 24 + this.h
}
// console.log(this.s);
//递归每秒调用countTime方法,显示动态时间效果
setTimeout(this.countTime, 1000);
}
最后回调一下这个函数就行了
mounted() {
this.countTime()
},
data() {
return {
d:'',
h: '',
m: '',
s: '',
sum_h: ''
}
}
以上就是全部代码了,根据需要来实现倒计时,有什么问题欢迎下方留言,一起讨论
更多推荐
已为社区贡献11条内容
所有评论(0)