移動端軟鍵盤監聽(彈出,收起),及影響定位布局的問題
一:移動端軟鍵盤監聽(彈出,收起)
1.監聽resize ( Android)
var winHeight = $(window).height(); //獲取當前頁面高度 $(window).resize(function () { var thisHeight = $(this).height(); if ( winHeight - thisHeight > 140 ) { //鍵盤彈出 } else { //鍵盤收起 } })
140是一個預估值的閥值,用來排除其他的resize操作。僅resize的高度差大於140時,才被識別為軟鍵盤交互,否則不是。如瀏覽器的工具欄、搜索欄的隱藏,window的窗口頁會有一個較小的變化。
2.監聽input失焦blur(IOS)
因為ios的第三方鍵盤可能並不會導致window resize,所以不能用resize監聽,但是可以通過輸入框是否獲取焦點來判斷; (在android中,點擊鍵盤上的收起按鈕,鍵盤雖然收起了,輸入框仍然處於焦點狀態,並沒有觸發focusout事件)
focusin和focusout支持冒泡,對應focus和blur, 使用focusin和focusout的原因是focusin和focusout可以冒泡,focus和blur不會冒泡,這樣就可以使用事件代理,處理多個輸入框存在的情況。(這個視情況而定)
$(document).on('focusin', function () { //軟鍵盤彈出的事件處理 }); $(document).on('focusout', function () { //軟鍵盤收起的事件處理 });
二:布局問題 (針對定位)
參考: 鏈接一
1.輸入框input獲取焦點時,虛擬鍵盤會把fixed元素頂上去(主要在部分安卓上)
$('#phone').bind('focus',function(){ $('.bottom_fix').css('position','static'); //或者$('#viewport').height($(window).height()+'px'); }).bind('blur',function(){ $('.bottom_fix').css({'position':'fixed','bottom':'0'}); //或者$('#viewport').height('auto'); });
2.屏幕旋轉時,出現上面問題
$(document).bind('orientationchange',function(){ if(window.orientation==90 || window.orientation==-90){ $('.bottom_fix').css('position','static'); }else{ $('.bottom_fix').css({'position':'fixed','bottom':'0'}); } });
3.iOS下Html頁面中input獲取焦點被彈出鍵盤遮擋
var u = navigator.userAgent, app = navigator.appVersion; var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios終端 if (isiOS) { window.setTimeout(function(){ window.scrollTo(0,document.body.clientHeight); }, 500); }