html5 虚拟键盘弹出挡住底部的输入框解决方案

问题描述:

  我们使用 h5 做移动网站开发时,如果文本框在页面的下方,当输入信息弹出的软键盘会将输入框挡住(Android 会有这个问题,IOS会自动将整个页面上移),IOS中软键盘关闭后,页面上移的部分不会自动下移,体验不是很好。

解决方案:

  可以借助元素的 scrollIntoView() 方法。scrollIntoView()可以在所有的HTML元素上调用。调用该方法后,则被调用的元素会出现在视图窗口中,并且元素会和视图窗口的顶部齐平。

代码实例:

  问题: 页面中有一个textarea 在页面的底部,软键盘弹出时会遮挡住textare.

  解决思路:

      1. 在textarea focus时调用scrollIntoView()方法

      2. 软键盘关闭后,即获取到textarea blur 时将页面滚动到顶部(解决ios 页面不自动下移的问题)

      3. 代码如下:

     <div style="height:800px"></div>
        <textarea onfocus="focusBlur('focus')" onblur="focusBlur('blur')"></textarea>
        <div style="height:300px"></div>
        <script>
            function focusBlur(state){
                if(state == 'focus'){
                   // document.querySelector('textarea').scrollIntoView();
                }else{
                    window.scroll(0,0); //页面返回到顶部
                }
            }
        </script>

  

原文地址:https://www.cnblogs.com/yangkangkang/p/7509840.html