文档管理中心
您当前正在浏览新版开发者文档中心,目录分类和层级有所调整。点击左侧当前文档分类名称前的“☰”图标,可切换文档分类。 了解新版目录
问题处理与运维开发与测试问题应用框架开发Web框架Web开发(ArkWeb)Web场景下主动拉起软键盘

Web场景下主动拉起软键盘

问题现象

Web组件加载H5页面,H5页面中有input输入框,如何实现刚进入H5页面就直接拉起软键盘?

背景知识

  • onPageEnd:网页加载完成时触发该回调,且只在主frame触发,iframe或者frameset的内容加载时不会触发此回调。
  • @ohos.inputMethod (输入法框架):本模块主要面向普通前台应用(备忘录、信息、设置等系统应用与三方应用),提供对输入法(输入法应用)的控制、管理能力,包括显示/隐藏输入法软键盘、切换输入法、获取所有输入法列表等等。

解决方案

H5页面有输入框时,可以在Web的onPageEnd回调中使用@ohos.inputMethod (输入法框架)框架的showTextInput方法实现页面加载时主动使输入框获焦并拉起键盘,inputMethod.TextConfig可以设置键盘的编辑框样式,attach方法将自绘控件与输入法绑定。

端侧示例代码如下:

收起
自动换行
深色代码主题
复制
  1. import { webview } from '@kit.ArkWeb';
  2. import { inputMethod } from '@kit.IMEKit';
  3. import { BusinessError } from '@kit.BasicServicesKit';
  4. let inputMethodController = inputMethod.getController();
  5. @Entry
  6. @Component
  7. struct WebComponent {
  8. controller: webview.WebviewController = new webview.WebviewController();
  9. build() {
  10. Scroll() {
  11. Column() {
  12. Web({
  13. src: $rawfile('keyBoardDemo.html'),
  14. controller: this.controller,
  15. })
  16. .onPageEnd(() => {
  17. try {
  18. let textConfig: inputMethod.TextConfig = {
  19. inputAttribute: {
  20. textInputType: 0,
  21. enterKeyType: 1
  22. }
  23. };
  24. inputMethodController.attach(true, textConfig, (err: BusinessError) => {
  25. if (err) {
  26. console.error(`Failed to attach: ${err.code} ${err.message}`);
  27. return;
  28. }
  29. console.info('Succeeded in attaching the inputMethod.');
  30. });
  31. } catch (err) {
  32. console.error(`Failed to attach: ${err.code} ${err.message}`);
  33. }
  34. inputMethodController.showTextInput().then(() => {
  35. console.info('Succeeded in showing text input.');
  36. }).catch((err: BusinessError) => {
  37. console.error(`Failed to showTextInput: ${err.code} ${err.message}}`);
  38. });
  39. })
  40. .fileAccess(false)
  41. .geolocationAccess(false)
  42. .domStorageAccess(true)
  43. .height('100%');
  44. };
  45. };
  46. }
  47. }

HTML示例代码如下:

收起
自动换行
深色代码主题
复制
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport"
  6. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <h1>H5侧</h1>
  11. <div>
  12. <input id="myInput" type="text" value="" style="margin:10px 0" onload/><br/>
  13. </div>
  14. </body>
  15. <script>
  16. function test() {
  17. document.getElementById("myInput").focus();
  18. }
  19. // 加载时立即执行此函数
  20. document.addEventListener('DOMContentLoaded', test);
  21. </script>
  22. </html>
  23. <style>
  24. body {
  25. width:100%;
  26. height:auto;
  27. margin:50px auto;
  28. text-align:center;
  29. }
  30. </style>

常见FAQ

Q:滚动时如何收起键盘?

A:滚动时键盘不消失是系统的默认逻辑,可以通过Web组件的onScroll回调中使用stopInputSession收起键盘。