解决键盘弹出后挡表单的问题

解决键盘弹出后挡表单的问题

// 解决键盘弹出后挡表单的问题
    window.addEventListener('resize', function() {
      if(
        document.activeElement.tagName === 'INPUT' ||
        document.activeElement.tagName === 'TEXTAREA'
      ) {
        window.setTimeout(function() {
          if('scrollIntoView' in document.activeElement) {
            document.activeElement.scrollIntoView();
          } else {
            document.activeElement.scrollIntoViewIfNeeded();
          }
        }, 0);
      }
    });

附个demo吧

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    * {
      box-sizing: border-box;
      padding: 0;
      margin: 0;
    }
    html,
    body {
      height: 100%;
    }
    .main {
      height: 100%;
      background-color: red;
    }
    .footer {
      position: absolute;
      bottom: 0;
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
    }
    textarea {
      flex: 2;
      height: 100%;
    }
    span {
      flex: 1;
      height: 100%;
      text-align: center;
      background-color: blue;
    }
  </style>
</head>
<body>
  <div class="main">
    main
  </div>
  <div class="footer">
    <textarea class="msg"></textarea>
    <span>发送</span>
  </div>
  <script>
    window.addEventListener('resize', function () {
      if (
        document.activeElement.tagName === 'INPUT' ||
        document.activeElement.tagName === 'TEXTAREA'
      ) {
        window.setTimeout(function () {
          if ('scrollIntoView' in document.activeElement) {
            document.activeElement.scrollIntoView()
          } else {
            document.activeElement.scrollIntoViewIfNeeded()
          }
        }, 0)
      }
    })
  </script>
</body>
</html>

未经允许不得转载:莫小奈博客 » 解决键盘弹出后挡表单的问题

评论 0

评论前必须登录!

登陆 注册