jQuery UI的日期选择器(datepicker)和时间选择器(timepicker)是常用的Web表单控件,但在移动设备上可能会与原生控件冲突或显示不理想。
移动设备通常有自带的日期/时间选择器,当检测到<input type="date">
或<input type="time">
时会自动显示原生控件。如果同时使用jQuery UI的选择器,会导致两个控件同时出现或交互冲突。
// 检测是否为移动设备
function isMobileDevice() {
return (typeof window.orientation !== "undefined") ||
(navigator.userAgent.indexOf('IEMobile') !== -1);
}
$(document).ready(function() {
if (!isMobileDevice()) {
// 只在非移动设备上初始化jQuery UI日期选择器
$("#datepicker").datepicker();
} else {
// 移动设备上使用原生HTML5日期控件
$("#datepicker").attr("type", "date");
}
});
$(document).ready(function() {
if (!Modernizr.touch) {
$("#datepicker").datepicker();
} else {
$("#datepicker").attr("type", "date");
}
});
@media (hover: none) and (pointer: coarse) {
.ui-datepicker {
display: none !important;
}
input[type="date"] {
display: block !important;
}
}
<!-- 日期选择 -->
<input type="date" id="datepicker">
<!-- 时间选择 -->
<input type="time" id="timepicker">
type="date"
和type="time"
支持良好,且移动设备上有更好的用户体验。$(document).ready(function() {
var dateInput = document.createElement('input');
dateInput.setAttribute('type', 'date');
if (dateInput.type !== 'date') {
// 浏览器不支持HTML5日期控件,使用jQuery UI
$("#datepicker").datepicker();
}
});
touchstart
事件替代click
事件以获得更好的触摸体验没有搜到相关的文章