// 让输入框显示在手机中间 输入区在底部
var keyboard = function(domEvent) {
// ISO手机处理
this.isReset = true; // 是否归位
this.focusinHandler = function() {
this.isReset = false; // 聚焦时键盘弹出,焦点在输入框之间切换时,会先触发上一个输入框的失焦事件,再触发下一个输入框的聚焦事件
};
this.focusoutHandler = function() {
this.isReset = true;
setTimeout(function() {
// 当焦点在弹出层的输入框之间切换时先不归位
if (this.isReset) {
window.scroll(0, 0); // 确定延时后没有聚焦下一元素,是由收起键盘引起的失焦,则强制让页面归位
}
}, 30);
};
// Android 手机处理
this.originHeight = document.documentElement.clientHeight || document.body.clientHeight;
this.resizeHandler = function() {
var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
// 当前获得焦点的元素
var activeElement = document.activeElement;
if (resizeHeight < this.originHeight) {
// 键盘弹起后逻辑
if (activeElement && (activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA")) {
setTimeout(function() {
// 让当前的元素滚动到浏览器窗口的可视区域内。
// activeElement.scrollIntoView({
// block: 'center'
// });
activeElement.scrollIntoViewIfNeeded;
}, 0)
}
} else {
// 键盘收起后逻辑
}
};
// 解绑事件
this.unmount = function() {
if (this.focusinHandler && this.focusoutHandler) {
domEvent.removeEventListener('focusin', this.focusinHandler);
domEvent.removeEventListener('focusout', this.focusoutHandler);
}
if (this.resizeHandler) {
window.removeEventListener('resize', this.resizeHandler);
}
}
// 入口函数
this.init = function(){
// 系统判断
var ua = window.navigator.userAgent.toLocaleLowerCase();
var isIOS = /iphone|ipad|ipod/.test(ua);
var isAndroid = /android/.test(ua);
if (isIOS) {
// console.info('isIOS')
// 上面 IOS 处理
domEvent.addEventListener('focus', this.focusinHandler);
domEvent.addEventListener('blur', this.focusoutHandler);
}
if (isAndroid) {
// 上面 Android 处理
// console.info('isAndroid')
window.addEventListener('resize', this.resizeHandler);
}
}
return this;
};