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

一、说明

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

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

二、表现

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

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

加了margin后原生键盘体现:web

三、代码

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 部分:bash

<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>
复制代码

示例图片:微信

相关文章
相关标签/搜索