【这里是 web-mobile 的解决方案,其它平台的未知】
部分安卓手机 H5 不支持通过脚本的方式唤起输入法(安卓系统问题),必须由 用户手动点击页面 input 才可以。
之前试了各种办法都不行(调用了很多 Cocos 接口都不行),最后做了个 hack 来解决 —— 生成个完全透明的 HTML input DOM 元素覆盖在 cocos 的 editbox 上面,点击 input 的时候再执行 editbox.focus() 并移除 input 就可以了。
我看最近论坛很多人吐槽这个问题,就顺手给大家我的解决方案吧。
代码参考:
private generateInput() {
if (!isAndroid) return;
const that = this;
const ipt = document.createElement('input');
ipt.setAttribute('id', 'input-for-focus');
const s = {
position: 'absolute',
zIndex: '99',
width: '4.7rem',
height: '0.57rem',
left: '1.4rem',
bottom: '7.1rem',
outline: 'none',
opacity: '0',
}
Object.keys(s).forEach(k => {
ipt.style[k] = s[k];
});
const editbox = this.node.getChildByPath('Dialog/EditNameContent/EditBox').getComponent(EditBox);
ipt.addEventListener('focus', () => {
editbox.focus();
that.removeInput();
})
document.body.appendChild(ipt);
}
private removeInput() {
if (isAndroid) {
const ipt = document.getElementById('input-for-focus');
if (ipt) {
document.body.removeChild(ipt);
}
}
}