1. 利用HTML5 input標(biāo)簽屬性type="date"
<input id="date" type="date" name="birthday" value="" placeholder="請(qǐng)?zhí)顚懩某錾掌? />
以上代碼在PC端的樣式為
在iPhone6s手機(jī)端的樣式為
默認(rèn)的placeholder樣式為:2016/09/14
注:
*PC端支持min和max日期限制(手機(jī)端不支持該特性)合陵,如想要限制年齡為22-49周歲抖部,js如下:
//保證年齡是22-49歲之間
var currYear = (new Date()).getFullYear();
var startYear = currYear - 49; //開始年份
var endYear = currYear - 22; //結(jié)束年份
var start=startYear+'-01-01';
var end=endYear+'-12-31';
$("input[name='birthday']").attr('min',start).attr('max',end);
*placeholder的CSS處理
input[type="date"] {
-webkit-appearance: none; /*清除樣式*/
background-color: transparent; /*清除背景色*/
}
input[type="date"]:before{
content: attr(placeholder);
color:#8f8f8f;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
color: #8f8f8f;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
color: #8f8f8f;
}
input:-ms-input-placeholder {
color: #8f8f8f;
}
input::-webkit-input-placeholder {
color: #8f8f8f;
}
/*設(shè)置calendar的樣式*/
::-webkit-datetime-edit-fields-wrapper { background-color: white; }
::-webkit-datetime-edit-text { color: #8f8f8f;}
::-webkit-datetime-edit-year-field { color: #8f8f8f; }
::-webkit-datetime-edit-month-field { color: #8f8f8f; }
::-webkit-datetime-edit-day-field { color: #8f8f8f; }
*最后還需要保證input值為空的時(shí)候placeholder自動(dòng)出現(xiàn)沸柔,js如下
//date日期的placeholder處理
var o = document.getElementById('date');
o.onfocus = function(){
this.removeAttribute('placeholder');
};
o.onblur = function(){
if(this.value == '') this.setAttribute('placeholder','請(qǐng)?zhí)顚懩某錾掌?);
};
2. 使用插件laydate.js
官網(wǎng):http://laydate.layui.com/
插件目錄:
頁面:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>layDate Demo</title>
<script src="laydate/laydate.js"></script>
</head>
<body>
<input class="laydate-icon" id="demo" value="">
</body>
<script>
;!function(){
laydate({
elem: '#demo'
})
}();
</script>
</html>
效果:
使用插件可以達(dá)到設(shè)置min和max日期的效果暑刃,如:
//日歷插件參數(shù)配置
;!function(){
//保證年齡是22-49歲之間
var currYear = (new Date()).getFullYear();
var startYear = currYear - 49; //開始年份
var endYear = currYear - 22; //結(jié)束年份
var start=startYear+'-01-01';
var end=endYear+'-12-31';
//日期范圍限制
var start = {
elem: '#date',
format: 'YYYY-MM-DD',
min: start, //設(shè)定最小日期為當(dāng)前日期
max: end, //最大日期
};
laydate(start);
}();
3. 使用插件laydate.js
Edit by 過山過水