摘要
个人觉得,计时器的js实现不难,难点在于如何设计计时器的样式,当然这篇文章中,我会把样式和js实现一起贴出来。
个人觉得,计时器的js实现不难,难点在于如何设计计时器的样式,当然这篇文章中,我会把样式和js实现一起贴出来。
注意,本篇文章中的所有代码只需要完全拷贝就能使用(至少你得知道这些东西放在哪个位置,否则还是需要先看学习下vue的)
首先标签如下:
<el-button type="primary" round :disabled="isAbleStart" @click="testTimer()">计时开始</el-button> <div> <div> <div> <div>{{myHours}}}</div> <div>时</div> </div> <span>:</span> <div> <div>{{myMinutes}}</div> <div>分</div> </div> <span>:</span> <div> <div>{{mySeconds}}</div> <div>秒</div> </div> </div> </div>
样式代码如下:
.dowebok { margin-top: 200px; align-items: center; } .timer { display: flex; flex-direction: row; justify-content: center; align-items: center; margin: 0 0 4em; color: #151414; } .time-card { margin: 0 1em; text-align: center; } .time-card-count { font-weight: 600; font-size: 70px; width: 77px; height: 77px; line-height: 77px; overflow: hidden; } .time-card-label { font-size: 0.625em; text-transform: uppercase; opacity: 0.7; } .colon { font-size: 2em; }
js如下:
data() { return { currentTime:0, timeObj: null, // 时间对象,下方会用到 myHours: '00', // 我定义来接收计算出来的 小时 的 myMinutes: '00', // 我定义来接收计算出来的 分钟 的 mySeconds: '00'// 我定义来接收计算出来的 秒钟 的 } }, methods: { testTimer(){ console.log("sdf"); this.timeFunction(); setInterval(() => { this.timeFunction(); }, 1000) },timeFunction(){ // 开始执行倒计时 this.timeObj = { // 时间对象 seconds: Math.floor(this.currentTime % 60), minutes: Math.floor(this.currentTime / 60) % 60, hours: Math.floor(this.currentTime / 60 / 60) % 24 } // 计算出时分秒 this.myHours = this.timeObj.hours<10?'0'+this.timeObj.hours:this.timeObj.hours; this.myMinutes = this.timeObj.minutes<10?'0'+this.timeObj.minutes:this.timeObj.minutes; this.mySeconds = this.timeObj.seconds<10?'0'+this.timeObj.seconds:this.timeObj.seconds; this.currentTime++; } }
实现出的效果如下:
稍微讲一下上面的逻辑,
testTimer
testTime方法为计时启动类,在未触发此方法前,计时器显示为:
当方法开始触发后,计时器立即开始运行,最大时长可到99小时59分59秒(你自己可以在前面加上天)。