H5页面有输入框时,可以在Web的onPageEnd回调中使用@ohos.inputMethod (输入法框架)框架的showTextInput方法实现页面加载时主动使输入框获焦并拉起键盘,inputMethod.TextConfig可以设置键盘的编辑框样式,attach方法将自绘控件与输入法绑定。
端侧示例代码如下:
import { webview } from '@kit.ArkWeb';
import { inputMethod } from '@kit.IMEKit';
import { BusinessError } from '@kit.BasicServicesKit';
let inputMethodController = inputMethod.getController();
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Scroll() {
Column() {
Web({
src: $rawfile('keyBoardDemo.html'),
controller: this.controller,
})
.onPageEnd(() => {
try {
let textConfig: inputMethod.TextConfig = {
inputAttribute: {
textInputType: 0,
enterKeyType: 1
}
};
inputMethodController.attach(true, textConfig, (err: BusinessError) => {
if (err) {
console.error(`Failed to attach: ${err.code} ${err.message}`);
return;
}
console.info('Succeeded in attaching the inputMethod.');
});
} catch (err) {
console.error(`Failed to attach: ${err.code} ${err.message}`);
}
inputMethodController.showTextInput().then(() => {
console.info('Succeeded in showing text input.');
}).catch((err: BusinessError) => {
console.error(`Failed to showTextInput: ${err.code} ${err.message}}`);
});
})
.fileAccess(false)
.geolocationAccess(false)
.domStorageAccess(true)
.height('100%');
};
};
}
} HTML示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>H5侧</h1>
<div>
<input id="myInput" type="text" value="" style="margin:10px 0" onload/><br/>
</div>
</body>
<script>
function test() {
document.getElementById("myInput").focus();
}
// 加载时立即执行此函数
document.addEventListener('DOMContentLoaded', test);
</script>
</html>
<style>
body {
width:100%;
height:auto;
margin:50px auto;
text-align:center;
}
</style>