随着网上购物平台不断增多,每个平台为了获得更多消费者的青睐,每个节日的福利秒杀成了必不可少的存在,微信小程序或者app中就常见到倒计时,本文实现了倒计时的功能。
实现效果:
实现上图图片中的倒计时功能
1、首先在页面中添加该元素
<view class="time">
<text>还剩</text>
<view class="shijian">{{countdownh}}</view>
<text>时</text>
<view class="shijian">{{countdownm}}</view>
<text>分</text>
<view class="shijian">{{countdowns}}</view>
<text>秒</text>
</view>
2、在data中声明变量
data () {
return {
countdownh:'',
countdownm:'',
countdowns:'',
timer: null, //重复执行
}
},
3、添加方法
onLoad() {
this.timer = setInterval(()=>{
this.showtime()
})
},
methods: {
showtime () {
var nowtime = new Date(), //获取当前时间
endtime = new Date("2021/12/10"); //定义结束时间
var lefttime = endtime.getTime() - nowtime.getTime(), //距离结束时间的毫秒数
leftd = Math.floor(lefttime/(1000*60*60*24)), //计算天数
lefth = Math.floor((lefttime/(1000*60*60)%24)+leftd*24) < 10 ? "0" + Math.floor((lefttime/(1000*60*60)%24)+leftd*24) : Math.floor((lefttime/(1000*60*60)%24)+leftd*24), //计算小时数
leftm = Math.floor(lefttime/(1000*60)%60) < 10 ? "0" + Math.floor(lefttime/(1000*60)%60) : Math.floor(lefttime/(1000*60)%60), //计算分钟数
lefts = Math.floor(lefttime/1000%60) < 10 ? "0" + Math.floor(lefttime/1000%60) : Math.floor(lefttime/1000%60); //计算秒数
this.countdownh = lefth //返回倒计时的字符串
this.countdownm = leftm//返回倒计时的字符串
this.countdowns = lefts //返回倒计时的字符串
// 倒计时结束时,显示00:00:00
if(lefttime < 0) {
this.countdownh = this.countdownm= this.countdowns = "00"
}
}
}
可根据自己所需要的显示方式来修改,到此,倒计时的功能就已完美实现!