小程序幹活系列----日期控件


一言不合就上圖: 
 
javascript

首先整合一些黑科技: 
1.每一個月的天數如何計算:new Date(year, month, 0).getDate() 
解釋說明:css

7.Find a value t such that YearFromTime(t) == ym and MonthFromTime(t) == mn) and DateFromTime(t) == 1; but if this is not possible (because some argument is out of range), return NaN. 
8.Return Day(t) + dt − 1.

上面這句話來自ES 規範:http://es5.github.io/#x15.9.1.12,這一節的第七和第八條,意思就是 
簡單解釋下就是,傳入 year, month, day 來獲取一個新的日期實例時,會先獲取指定年、月的 1 號,例如 year=2017, month=4,會先獲取 2017-5-1 這個日期,這是上面第七步完成的。 
而後第八步,上面這個日期會加上 day 參數的整數值,而後減去 1。 
上面的話通俗一點講就是:new Date(2018, 5, 0).getDate()這個獲取的是2018年4月最後一天的日期前端

2.每一個月第一天是周幾的計算:new Date(year, month - 1, 1).getDay()java

獲取到當前月的總天數和1號對應的是星期幾是否是瞬間感受日曆控件的邏輯也沒有特別複雜了呢git

具體實現步驟說明:github

1.界面採用flex佈局,當超過七個值時自動往下一行進行排列 
2.實現日期前面的空白採用倆個for循環,第一個for循環循環空白值,第二個for循環循環日期值,空白值數組的長度等於當前月1號周幾的長度express

<view class="days box box-lr box-wrap">   <view wx:if="{{hasEmptyGrid}}" class="grid white-color box box-align-center box-pack-center" wx:for="{{empytGrids}}" wx:key="{{index}}" data-idx="{{index}}"></view>   <view class="grid white-color box box-align-center box-pack-center" wx:for="{{days}}" wx:key="{{index}}" data-idx="{{index}}">     <view bindtap='changeDate' data-index='{{index+1}}' class="day {{(index+1) ==today ? (curMonth==cur_month? 'border-radius pink-bg':'border-radius pink-bd') : ''}} box box-align-center box-pack-center">{{item}}</view>   </view></view>

3.選擇日期的時候圓圈跟隨變化,切換月份的時候變成無填充邊框圓圈segmentfault

<view class="day {{(index+1) ==today ? (curMonth==cur_month? 'border-radius pink-bg':'border-radius pink-bd') : ''}} box box-align-center box-pack-center">{{index+1}}</view>

使用步驟: 
1.將date模板導入項目最外層 
2.wxml頁面添加數組

<import src="/date/date.wxml" /><template is="date" data="{{weeks_ch,cur_year,cur_month,hasEmptyGrid,empytGrids,days,today,curMonth}}" />

3.wxss頁面添加微信

@import "/date/date.wxss";

4.js頁面添加

var date = require('../../date/date.js');

5.在onLoad初始化日期控件

onLoad: function (options) {
    date.dateInit(this);
  }

相關代碼連接(後期會添加到github上和碼雲上): 
https://blog.csdn.net/m0_37479946/article/details/79795215

日期控件這種需求仍是比較常見的,博主在這裏實現的是選擇指定日期返回值得方式。下次碰到連續選擇日期的需求,博主也會整合進來。將會對這個日期控件持續進行擴展,要是評論數超過二十條樓主也會考慮實現這個功能的

參考連接: 
https://segmentfault.com/q/1010000011402629?sort=created 
初始日曆控件是朋友給的,不知道地址。忘做者見諒

喜歡我能夠關注個人公衆號,更多精彩內容能夠早一步觀看 


本文分享自微信公衆號 - 點滴前端(DDIWEB)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索