欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js解决软键盘遮挡输入框的问题分享

程序员文章站 2022-05-04 14:54:11
经验须知 弹出软键盘时: ios端$(‘body').scrolltop()会改变 android端$(window).height()会改变 拉起键盘不是一瞬间...

经验须知

弹出软键盘时:

ios端$(‘body').scrolltop()会改变

android端$(window).height()会改变

拉起键盘不是一瞬间,而是有一个缓动过程

问题重现

ios端,经常会出现输入法遮挡输入框的问题(特别是那种有一个白色顶部的输入法,如:百度输入法),如图:

js解决软键盘遮挡输入框的问题分享

问题解决

我们只需要在输入框聚焦之后,开启一个定时器,执行$(‘body').scrolltop(1000000),这样由于整个body滚动到了最下面,输入框自然就看见了,具体请查看以下示例

示例源码

<!doctype html> 
<html lang="en"> 
<head> 
  <meta charset="utf-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"> 
  <meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1"/> 
  <title>demo</title> 
  <script src="../js/jquery-1.11.3.min.js"></script>
  <style> 
    * { 
      margin: 0;  
      padding: 0; 
    } 
    body, html { 
      width: 100%; 
      height: 100%;
    } 
    .bottom {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      font-size: 0;
    }
    input {
      font-size: 14px;
      box-sizing: border-box;
      width: 50%;
      height: 50px;
      line-height: 50px;
    }
  </style> 
</head> 
<body>
  <div class="bottom">
    <input class="ainput" type="text" placeholder="ios聚焦后会被输入法遮挡" />
    <input class="binput" type="text" placeholder="ios聚焦后不会被输入法遮挡" />
  </div>
</body> 
<script> 
  $(function() {
    // 解决输入法遮挡
    var timer = null;
    $('.binput').on('focus', function() {
      clearinterval(timer);
      var index = 0;
      timer = setinterval(function() {
        if(index>5) {
          $('body').scrolltop(1000000);
          clearinterval(timer);
        }
        index++;
      }, 50)
    })
  });

</script> 
</html>

以上这篇js解决软键盘遮挡输入框的问题分享就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。