移动端键盘顶起遮挡输入框&offsetTop值不准问题

先上图

 

 通常在开发中我们会遇到这样输入框被遮挡的问题,那么该怎么解决呢?
方案一(css):

首先,把置底元素设置成,在页面的底部而非屏幕的底部

.page .bottom {
    position: absolute;
    bottom: 0;
     100%;
    border: 0;
    text-align: center;
    z-index: 5;
}

然后,设置页面的高度,让按钮有置底的效果

.page {
    background: #fff;
    color: #384369;
    position: relative;
     100%;
    overflow-y: auto;
    height: 100vh;
    min-height: 480px;
}

注意有最小高度,因为当键盘弹起时,100vh是缩小的那部分的高度,而不是屏幕高度
*如果有大屏的需求,适配一下就好

这样,当键盘弹起时,内容就是可以滚动的了,出于用户体验的需求,可以在focus输入框的时候,把滚动条划一下,露出输入框

function whenFocus(){
        document.body.scrollTop = document.documentElement.scrollTop =86;
}

具体的数值可以再调整

方案二(css):
<div class="main">
    <div class="content"></div>
    <button></button>
</div>

设置content为 overflow: auto;
让content的高度为 100vh-buttonHeight

方案三(flex布局):

使用第二种的html

.main{
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
   .content {
        overflow: auto;
    }
}

 

方案四(js):

其实,当移动端弹起键盘的时候会触发window的onresize事件,把webview的高度变小了,知道了这个我们就可以用js来操作

 给input或者textarea绑一个onfocus事件

scrollIntoView(v,e){
setTimeout(() => {
window.scrollTo(0, e.target.offsetTop)
},500)
},

注意:当输入框的父元素使用了position:relative的时候,输入框的offsetTop的值就会有问题

原文地址:https://www.cnblogs.com/mingweiyard/p/10730344.html