我們在做移動(dòng)web應(yīng)用的時(shí)候,常常習(xí)慣于使用position:fixed把一個(gè)input框作為提問或者搜索框固定在頁面底部。但在IOS的safari和webview中,對position:fixed的支持不是很好(在IOS5之前甚至還不支持position:fixed)。我遇到的其中一個(gè)問題就是,在iOS6+環(huán)境下,input focus彈出輸入法的時(shí)候,設(shè)置了position fixed的input框浮在頁面上了,而不是吸附在軟鍵盤上。
解決方案:
基于zepto的主要代碼實(shí)現(xiàn)如下:
$('input').focus(function(){
var _this = this;
//無鍵盤時(shí)輸入框到瀏覽器窗口頂部距離
var noInputViewHeight = $(window).height() - $(_this).height();
//網(wǎng)頁正文內(nèi)容高度
var contentHeight = $(document).height() - $(_this).height();
//控制正文內(nèi)容高度大于一屏,保證輸入框固定底部
contentHeight = contentHeight > noInputViewHeight ? contentHeight : noInputViewHeight;
//因?yàn)閺棾鲚斎敕ㄐ枰獣r(shí)間,需延時(shí)處理
setTimeout(function(){
//彈出輸入法時(shí)滾動(dòng)條的起始滾動(dòng)距離
var startScrollY = $(window).scrollTop();
//彈出輸入法時(shí)輸入框到窗口頂部的距離,即到軟鍵盤頂部的起始距離
var inputTopHeight = $(_this).offset().top - startScrollY;
//彈出輸入法時(shí)輸入框預(yù)期位置,即緊貼軟鍵盤時(shí)的位置。因輸入框此時(shí)處于居中狀態(tài),所以其到窗口頂部距離即為需往下移動(dòng)的距離。
var inputTopPos = $(_this).offset().top + inputTopHeight;
//控制div不超出正文范圍
inputTopPos = inputTopPos > contentHeight ? contentHeight : inputTopPos;
//設(shè)置輸入框位置使其緊貼輸入框
$(_this).css({'position':'absolute', 'top':inputTopPos });
//給窗口對象綁定滾動(dòng)事件,保證頁面滾動(dòng)時(shí)div能吸附軟鍵盤
$(window).bind('scroll', function(){
//表示此時(shí)有軟鍵盤存在,輸入框浮在頁面上了
if (inputTopHeight != noInputViewHeight) {
//頁面滑動(dòng)后,輸入框需跟隨移動(dòng)的距離
var offset = $(this).scrollTop() - startScrollY;
//輸入框移動(dòng)后位置
afterScrollTopPos = inputTopPos + offset;
//設(shè)置輸入框位置使其緊貼輸入框
$(_this).css({'position':'absolute', 'top':afterScrollTopPos });
}
});
}, 100);
}).blur(function(){//輸入框失焦后還原初始狀態(tài)
$(".div-input").removeAttr('style');
$(window).unbind('scroll');
});