帮我写一段微信小程序点击按钮开始计时再次点击计时停止的完整代码
时间: 2023-04-06 15:02:34 浏览: 119
好的,以下是微信小程序点击按钮开始计时再次点击计时停止的完整代码:
wxml文件:
```
<view class="container">
<view class="timer">{{time}}</view>
<button class="btn" bindtap="startTimer">{{btnText}}</button>
</view>
```
js文件:
```
Page({
data: {
time: '00:00:00',
btnText: '开始计时',
timer: null,
startTime: 0,
endTime: 0
},
startTimer: function() {
if (this.data.timer) {
clearInterval(this.data.timer);
this.setData({
timer: null,
btnText: '开始计时'
});
this.data.endTime = new Date().getTime();
console.log('计时结束,用时:' + (this.data.endTime - this.data.startTime) / 1000 + '秒');
} else {
this.setData({
timer: setInterval(this.updateTime, 1000),
btnText: '停止计时'
});
this.data.startTime = new Date().getTime();
console.log('计时开始');
}
},
updateTime: function() {
var time = new Date().getTime() - this.data.startTime;
var hour = Math.floor(time / 3600000);
var minute = Math.floor((time - hour * 3600000) / 60000);
var second = Math.floor((time - hour * 3600000 - minute * 60000) / 1000);
this.setData({
time: this.formatTime(hour) + ':' + this.formatTime(minute) + ':' + this.formatTime(second)
});
},
formatTime: function(num) {
return num < 10 ? '0' + num : num;
}
})
```
CSS文件:
```
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.timer {
font-size: 48rpx;
margin-bottom: 32rpx;
}
.btn {
width: 200rpx;
height: 80rpx;
font-size: 32rpx;
background-color: #4CAF50;
color: #fff;
border-radius: 10rpx;
border: none;
outline: none;
}
```
希望这个代码能够帮到你!