微信小程序下訂單插件(日歷)


最近做小程序開發,出於練手,也是工作需要,就做了個微信小程序的類似於酒店預訂的日歷插件。
先上圖;

 


這個插件分為上下兩部分,上邊是tab欄,會根據當前的日期自動定位到當前,並展示以后7天的日期,下邊為內容展示,隨tab欄變化而變化。
思路:
首先用`new Data()`時間對象初始化時間,獲取當前的日期,用`new Date(Date.UTC(year, month - 1, 1)).getDay()`獲取每個月的第一天是星期幾。

// 計算每月第一天是星期幾
function getFirstDayOfWeek(year, month) {
return new Date(Date.UTC(year, month - 1, 1)).getDay();
}
const date = new Date();
const cur_year = date.getFullYear();
const cur_month = date.getMonth() + 1;
const cur_date=date.getDate();
const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];

利用構造函數生成數據,一會用。

//利用構造函數創建對象
function calendar(date,week){
this.date=cur_year+'-'+cur_month+'-'+date;
if(date==cur_date){
this.week = "今天";
}else if(date==cur_date+1){
this.week = "明天";
}else{
this.week = '星期' + week;
}
}

使用for循環生成json數據:

for(var i=1;i<=monthLength;i++){
//當循環完一周后,初始化再次循環
if(x>6){
x=0;
}
//利用構造函數創建對象
that.data.calendar[i] = new calendar(i, [weeks_ch[x]][0])
x++;
}

這里因為一周有7天,所以當x>6的時候,重置為0。
最后展示部分源碼

var that=this;
function getThisMonthDays(year, month) {
return new Date(year, month, 0).getDate();
}
// 計算每月第一天是星期幾
function getFirstDayOfWeek(year, month) {
return new Date(Date.UTC(year, month - 1, 1)).getDay();
}
const date = new Date();
const cur_year = date.getFullYear();
const cur_month = date.getMonth() + 1;
const cur_date=date.getDate();
const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
//利用構造函數創建對象
function calendar(date,week){
this.date=cur_year+'-'+cur_month+'-'+date;
if(date==cur_date){
this.week = "今天";
}else if(date==cur_date+1){
this.week = "明天";
}else{
this.week = '星期' + week;
}
}
//當前月份的天數
var monthLength= getThisMonthDays(cur_year, cur_month)
//當前月份的第一天是星期幾
var week = getFirstDayOfWeek(cur_year, cur_month)
var x = week;
for(var i=1;i<=monthLength;i++){
//當循環完一周后,初始化再次循環
if(x>6){
x=0;
}
//利用構造函數創建對象
that.data.calendar[i] = new calendar(i, [weeks_ch[x]][0])
x++;
}
//限制要渲染的日歷數據天數為7天以內(用戶體驗)
var flag = that.data.calendar.splice(cur_date, that.data.calendar.length - cur_date <= 7 ? that.data.calendar.length:7)
that.setData({
calendar: flag
})
//設置scroll-view的子容器的寬度
that.setData({
width: 186 * parseInt(that.data.calendar.length - cur_date <= 7 ? that.data.calendar.length : 7)
})

最后奉上github地址:

 

github地址


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM