利用flex布局解决ios输入框被键盘遮挡问题

3,685 阅读2分钟

1、说明

网上有很多类似例子,我自己也使用vue写一个简单的demo,主要利用flex布局,解决ios端偶现的,fixed或者absolute布局导致的输入框被键盘遮挡问题,至于键盘收起页面卡住等其他问题 请参考链接:h5页面在不同ios设备上的问题总结 ,本demo暂时不考虑。

原理是:使用flex布局,把要滚动的区域置于底层滚动。

2、表现

在手机端,微信浏览器和qq浏览器,钉钉浏览器等,都表现的不错,在safri浏览器会有底部固定效果失效的问题,这个问题比较严重,我还没来得及仔细研究原因

另外,如果手机安装了第三方输入法,比如搜狗输入法,还是会有遮挡问题 ,使用原生键盘没有问题,本demo中,为了解决这个问题,在聚焦的时候,给底部加了一个margin,如果谁有好的办法,请给我留言

加了margin后原生键盘体现:

3、代码

html部分:一个父节点,两个子节点,父节点:flex-test,子节点:一个是要滚动的区域content,一个是footer,固定在底端

<template>
  <div class="flex-test">
    <!-- 内容区域 -->
    <content class="content">
        <!-- 头部 -->
        <header class="header">header</header>
         <ul v-for="(item,index) in datalist" :key="index">
            <li>{{item}}</li>
         </ul> 
    </content>
    <!-- 底部输入框部 -->
    <footer class="footer">
      <input type="text" class="input">
      <button class="button">submit</button>
    </footer>
  </div>
</template>

js部分:为了体现滚动效果,可以给数组加长,我只写了三项是为了文档简洁。

<script>
export default {
  name: "pagetest",

  data() {
    return {
        datalist:[
            "body数据body数据body数据body数据body数据",
            "body数据body数据body数据body数据body数据",
            "body数据body数据body数据body数据body数据",
        ]
    };
  },
  mounted() {
  
  //这个是给底部固定加一个margin高度,为了解决第三方输入法遮挡问题,当然切换到原生键盘,也会高出一些
    document.querySelector("input").addEventListener("focus", () => {
      document.querySelector("footer").style.marginBottom = "20px";
    });
  },
};
</script>

css 部分:

<style scoped lang="scss">
.flex-test {
  display: flex; // 设置flex
  flex-direction: column;
  height: 100vh;  //设置高度为屏幕高度
  
  .content {
    flex: 1;    //这部分内容置于底层,这样content以外的节点,都会在顶层
    overflow: auto;  //超过一屏滚动
    -webkit-overflow-scrolling: touch;
  }
}

//后面那些css 没什么特殊的,正常按照你的习惯,写底部的样式就行了
.header {
  height: 5rem;
}
.footer {
  height: 3rem;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background: #ccc;
  padding: 0 2rem;
  .input {
    width: 200px;
    height: 30px;
     border-radius: 4px;
  }
  .button {
    width: 50px;
    height: 30px;
    background: #fff;
    border-radius: 4px;
  }
}
</style>

示例图片: