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