問題:
今天一個頁面中,需要讓用戶選擇日期,準備使用input=date標簽,直接觸發(fā)移動端自帶的datepicker,結果在iOS端測試發(fā)現(xiàn)兩個問題,1.date標簽右側會有一塊空白,和其它元素對不齊(可能是系統(tǒng)默認留出了一個選擇按鈕的位置) 2.選擇完成以后顯示的格式為“yyyy年MM月dd”,我需要顯示到頁面上的格式是"yyyy-MM-dd"。
資料:
網(wǎng)上查資料說input[date]的樣式各個瀏覽器不統(tǒng)一,比較難調,比較好的解決方案是使用js插件來做datePicker,或者使用input[text]來代替input[date]。
解決思路:
源碼是angularjs,所以想寫一個directive來控制input標簽,初始使用text,用戶點擊input的時候把標簽切換為date,當用戶選擇完成,失去焦點后把input還原成text并格式化顯示的時間格式為“yyyy-MM-dd”
htm代碼
<ion-item class="item-input"><span class="input-label">復業(yè)日期</span>
<input type="text" date-picker="yyyy-MM-dd" ng-model="data.recoverDate">
<arrow></arrow>
</ion-item>
directive代碼
.directive('datePicker', function () {
return {
restrict: 'AE',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
element.bind('click', function () {
attrs.$set('type', 'date'); //input 類型改為type
});
element.bind('blur', function () {
attrs.$set('type', 'text'); //input 類型改回text
var formatString = attrs.datePicker ? attrs.datePicker : 'yyyy-MM-dd'; //如果沒有設置格式,默認為"yyyy-MM-dd"
var newValue = new Date(ctrl.$viewValue).format(formatString);
ctrl.$setViewValue(newValue);
ctrl.$render();
});
}
}
遇到的問題
1.寫directive的時候發(fā)現(xiàn)綁定focus事件,在iOS端彈不出datePicker,綁定click事件就可以,不知道為什么。
2.iOS測試沒有問題了,安卓還沒有測試,等有時間再測試、修改、優(yōu)化。