移动端软键盘监听(弹出,收起),及影响定位布局的问题

一:移动端软键盘监听(弹出,收起)    

  参考: 链接一   链接二        

     1.监听resize ( Android

1
2
3
4
5
6
7
8
9
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不会冒泡,这样就可以使用事件代理,处理多个输入框存在的情况。(这个视情况而定)

 

1
2
3
4
5
6
7
$(document). on ( 'focusin' , function () {
   //软键盘弹出的事件处理
});
  
$(document). on ( 'focusout' , function () {
   //软键盘收起的事件处理
});

 

  

二:布局问题 (针对定位

  参考: 链接一

       1.输入框input获取焦点时,虚拟键盘会把fixed元素顶上去(主要在部分安卓上)

1
2
3
4
5
6
7
$( '#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.屏幕旋转时,出现上面问题

1
2
3
4
5
6
7
$(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获取焦点被弹出键盘遮挡

 

1
2
3
4
5
6
7
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); 
}

 

猜你喜欢

转载自blog.csdn.net/qq_33834489/article/details/80450950