1、新建一个js文件softKeyboard.js

核心思想:在唤起软键盘之前,记录当前页面滚动位置(方便后面恢复位置);在软键盘关闭后,IOS端再将页面归位;

var u = navigator.userAgent;
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
let blur = () =>{
  if (isiOS) {
    document.body.scrollTop = 0;
    window.scrollTo(0, 0);
  }
};

let focusInput = () => {
  var node = document.activeElement;
  if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
    window.addEventListener("resize", function () {
      if (node.tagName == "INPUT" || node.tagName == "TEXTAREA") {
        window.setTimeout(function () {
          document.activeElement.scrollIntoViewIfNeeded();
        }, 0);
      }
    })
  }

  if (isiOS) {
    let offsetTop = node.offsetTop;
    setTimeout(() => {
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

      if(scrollTop <= 0) {
        document.body.scrollTop = offsetTop;
      }
    },300)
  }
};

export default {
  blur,
  focusInput
};

2、在main.js里面引入

// 软键盘弹起bug
import keyboard from '@/utils/softKeyboard'
Vue.prototype.$blur = keyboard.blur;
Vue.prototype.$focus = keyboard.focusInput;

3、在页面中使用如下

<input type="tel" pattern="[0-9]*" @input="mobile=mobile.slice(0,11)" v-model="mobile" @focus="$focus" @blur="$blur" placeholder="请输入您的手机号">

 这样就完美解决了。

posted on 2021-03-01 13:32  白不了的黑发  阅读(247)  评论(0编辑  收藏  举报