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

【关键字】

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

 

【写在前面】

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

cke_515.pngcke_781.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));
            }
        })
    },
}

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

 

【参考文档】

https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/js-apis-window-0000001477981397-V3#ZH-CN_TOPIC_0000001573929313__%E5%AF%BC%E5%85%A5%E6%A8%A1%E5%9D%97

posted @ 2023-08-01 10:36  Mayism123  阅读(139)  评论(0编辑  收藏  举报