当前位置: 首页 > news >正文

【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

http://www.lryc.cn/news/105634.html

相关文章:

  • day19-二叉树的最大最小深度
  • Ansible-roles
  • NullPointerException导致手机重启案例分析
  • JAVA 反编译工具
  • (AcWing)分组背包问题
  • JSP项目国际化词条统计
  • Java课题笔记~ MyBatis缓存
  • 数据结构--循环队列、链队
  • hbuilderx主题色分享-github风格
  • 【C++】类与对象(1)
  • Java课题笔记~ MyBatis核心配置
  • 从0开始自学网络安全(黑客)
  • kotlin 编写一个简单的天气预报app(四)增加界面显示
  • 英语不好能学好Python吗?Python常用英文单词汇总
  • Counting Stars 2023“钉耙编程”中国大学生算法设计超级联赛(5)hdu7335
  • 浅谈document.write()输出样式
  • AIGC(Artificial Intelligence and Graph Computing)职业发展路径和前景如何?
  • MySql006——基本的SELECT查询语句
  • 【啥都生】分类项目中的模型搭建代码解析
  • Ubuntu出现了内部错误
  • Stable Diffusion AI绘画初学者指南【概述、云端环境搭建】
  • 小程序动态隐藏分享按钮
  • 语音合成是什么?如何进行语音合成TTS数据采集?
  • 实用干货!一文读懂Salesforce中6种数据关系类型!
  • Spring引入外部数据源
  • word里的页码问题
  • ​LeetCode解法汇总142. 环形链表 II
  • 危化品行业防雷检测综合解决方案
  • 刷题笔记:day 1
  • Linux——平台设备及其驱动