天天看點

H5頁面移動端IOS鍵盤收起焦點錯位

出現場景:IOS端,在彈出層點選input時調起鍵盤頁面會被頂上去document.body.scrollOffset大于0,收起鍵盤時scrollOffset不變,造成焦點錯位。

注:安卓手機點選時調起鍵盤不會把頁面頂上去,會改變視窗高度變化,收起時不會造成影響。

jq處理:

1 $('input').on('blur', function (event) {
2   if (!(event.relatedTarget && event.relatedTarget.tagName)) document.body.scrollTop = 0;
3 });      

vue處理:

1、判斷移動端裝置

1 //判斷 IOS 或者 Android
 2 let u = window.navigator.userAgent;
 3 //IOS終端
 4 let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
 5 //android終端
 6 let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
 7 //IOS
 8 if(isiOS) return "IOS";
 9 //Android
10 if(isAndroid) return "Android";      

2、回歸原本高度

1 let type = "目前機型";//Android or IOS
 2 let isReset = true;//是否歸為
 3 if (type === 'IOS') {
 4     document.body.addEventListener('focusin', () => {
 5         //軟鍵盤彈出的事件處理
 6         isReset = false;
 7     });
 8     document.body.addEventListener('focusout', () => {
 9         //軟鍵盤收起的事件處理
10          isReset = true;
11          setTimeout(() => {
12              //當焦點在彈出層的輸入框之間切換時先不歸位
13              if (isReset)    window.scroll(0, 0);//失焦後強制讓頁面歸位
14          }, 100);
15      });
16  } else if (type === 'Android') {
17      window.onresize = function () {
18          //鍵盤彈起與隐藏都會引起視窗的高度發生變化
19          let resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
20          if (resizeHeight < h)    isReset = false;
21          else {
22              isReset = true;
23              setTimeout(() => {
24                   if (isReset)    window.scroll(0, 0);//失焦後讓頁面歸位
25               }, 100);
26           }
27       }
28   }       

轉載于:https://www.cnblogs.com/lyzw-Y/p/10783933.html

繼續閱讀