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