目录

HarmonyOS键盘遮挡输入框时,实现输入框显示在键盘上方

目录

【HarmonyOS】键盘遮挡输入框时,实现输入框显示在键盘上方

【关键字】

harmonyOS、键盘遮挡input,键盘高度监听

【写在前面】

在使用API6、API7开发HarmonyOS应用时,常出现页面中需要输入input,但是若input位置在页面下方,在input获取焦点的时候,会出现软键盘挡住input情况,对于这个问题,这里介绍如何在input获取焦点时,将input显示在键盘上方功能,键盘收起时,将input回归到原位,即如下效果:

https://i-blog.csdnimg.cn/blog_migrate/3ba8b8787d3a9420ba8f86793c1feaf9.png

https://i-blog.csdnimg.cn/blog_migrate/a35ba2e7affdb703a9c3e3b5287ab3ab.png

【页面布局】

首先我们编写一个简单的页面,这里直接将页面input设置在页面底部,代码如下:

// index.html
<div class="container">
    <input onfocus="foucs" value="{{inputVal}}" placeholder="请输入内容"
           style="position: absolute;bottom: {{keyboardHeight}}px;"></input>
</div>

【页面样式】

简单给input设置宽高,代码如下:

.container {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
}

input {
width: 100%;
height: 40px;
border-radius: 10px;
}

【页面逻辑】

当 input 获取焦点时,通过  @ohos.window 相关接口监听键盘高度变化,从而改变 input 位置,代码如下:

import window from '@ohos.window'

export default {
data: {
keyboardHeight: 0,
},
onInit() {

    },
    foucs() {
        console.info("foucs");
        let windowClass = null;
        window.getTopWindow((err, data) => {
            if (err) {
                console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));
                return;
            }
            windowClass = data;
            console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
            try {
                // 开启键盘高度变化的监听
                windowClass.on("keyboardHeightChange", (data) => {
                    console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data));
                    let height = data.height;

                    // 键盘弹起时设置input高度
                    if (this.keyboardHeight != height) {
                        this.keyboardHeight = height % 3.8;
                        console.info("keyboardHeightChange keyboardHeight:" + this.keyboardHeight)
                    }
                })
            } catch (exception) {
                console.error('Failed to enable the listener for keyboard height changes. Cause: ' + JSON.stringify(exception));
            }
        })
    },

}

这样就实现输入框显示在键盘上方效果了

【参考文档】