微信小程序小应用:实现一个日历打卡的功能。我们先看看演示效果:
废话不多说啊,我们直接来看代码吧。
wxml
<view class="context">
<view class="top">
<image src="../../img/left.png" bindtap="bindPreMonth"></image>
<view>{{year}}年{{month}}月</view>
<image src="../../img/right.png" bindtap="bindNextMonth"></image>
</view>
<view class="middle">
<view wx:for="{{data_arr}}" wx:key="index" class="middle_num">
{{item}}
</view>
</view>
<view class="calen">
<view wx:for="{{startWeek}}" wx:key="index" class="calen_blank"></view>
<view wx:for="{{currentMonthDays}}"
class='{{index+1 == today ? "active": "calen_num"}}'
wx:key="index">
{{index+1}}
</view>
</view>
</view>
JS
Page({
/**
* 页面的初始数据
*/
data: {
data_arr:["日","一","二","三","四","五","六"],
year:"",
month:"",
today:2 //这是固定2号这天打开,连续几天打卡就用数组就好了
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let now = new Date()
let year = now.getFullYear()
// month获取是从 0~11
let month = now.getMonth() + 1
this.setData({
year,month
})
this.showCalendar()
},
showCalendar(){
let {year,month} = this.data
//以下两个month已经+1
let currentMonthDays = new Date(year,month,0).getDate() //获取当前月份的天数
let startWeek = new Date(year + '/' + month + '/' + 1).getDay(); //本月第一天是从星期几开始的
this.setData({
currentMonthDays,startWeek
})
},
//上个月按钮
bindPreMonth(){
let {year,month} = this.data
//判断是否是1月
if(month - 1 >= 1){
month = month - 1
}else{
month = 12
year = year - 1
}
this.setData({
month,year
})
this.showCalendar()
},
//下个月按钮
bindNextMonth(){
let {year,month} = this.data
//判断是否是12月
if(month + 1 <= 12){
month = month + 1
}else{
month = 1
year = year + 1
}
this.setData({
month,year
})
this.showCalendar()
}
})
CSS
.context{
width: 96%;
background-color: antiquewhite;
margin: 0 auto;
padding: 10rpx;
}
.top{
height: 80rpx;
display: flex;
justify-content: space-around;
}
.top image{
height: 30rpx;
width: 30rpx;
}
.middle{
display: flex;
}
.middle_num{
width: 14%;
display: flex;
justify-content: center;
align-items: center;
}
.calen{
display: flex;
height: 400rpx;
flex-wrap: wrap; /* 必要的时候拆行或拆列。 */
}
.calen_blank{
width: 14%;
height: 20%;
background-color: pink;
}
.calen_num{
width: 14%;
height: 20%;
display: flex;
justify-content: center;
align-items: center;
}
.active{
background-color: rgb(89, 111, 238);
width: 14%;
height: 20%;
display: flex;
justify-content: center;
align-items: center;
border-radius: 40rpx;
}
大家可以方式微信小程序开发软件里去试试吧。