简体   繁体   English

我可以通过javascript(没有phonegap)触发Android软键盘打开吗?

[英]Can I trigger Android soft keyboard to open via javascript ( without phonegap )?

I have some custom web components in my mobile web app, whereas I need to manually fire 'focus' events on a field, to simulate the 'NEXT' functionality in the Android soft keyboard feature.我的移动 Web 应用程序中有一些自定义 Web 组件,而我需要在字段上手动触发“焦点”事件,以模拟 Android 软键盘功能中的“NEXT”功能。 ( using Galaxy S3 native browser ). (使用 Galaxy S3 原生浏览器)。

However, when I manually fire a focus event on a 'select' field, the native soft keyboard does not show.但是,当我在“选择”字段上手动触发焦点事件时,本机软键盘不会显示。 I have to subsequently click on the field to get it to show.我必须随后单击该字段以使其显示。 (In IOS, of course, it works just fine). (当然,在 IOS 中,它工作得很好)。

So I'm wondering, if a 'focus' event doesn't trigger the soft keyboard to open, what JS event will ???所以我想知道,如果“焦点”事件没有触发软键盘打开,什么 JS 事件会???

I am not using phonegap so I'm hoping there's a way without it.我没有使用 phonegap,所以我希望有一种没有它的方法。

Thanks for any help!!!谢谢你的帮助!!!

Here's a link from StackOverflow:这是来自 StackOverflow 的链接:

Showing Android's soft keyboard when a field is .focus()'d using javascript 使用 javascript 对字段进行 .focus() 处理时显示 Android 的软键盘

Just focussing without an event doesnt seem to work.只是在没有事件的情况下集中注意力似乎不起作用。 - you DO need a click event triggering this. - 你确实需要一个点击事件来触发这个。

$(document).ready(function() {
    $('#field').click(function(e){
        $(this).focus();
    });
    $('#button').click(function(e) {
        $('#field').trigger('click');
    });
});

You can do this by calling focus() then click() on the input.您可以通过在输入上调用focus()然后click()来做到这一点。 No need for jquery.不需要jquery。 Beware of endless loops if your script is triggered by an onclick() on a containing element.如果您的脚本由包含元素上的 onclick() 触发,请注意无限循环。 Make sure as well that this script is triggered by some user interaction.还要确保此脚本是由某些用户交互触发的。 It won't work from document.onload(), or from a setTimeout().它不适用于 document.onload() 或 setTimeout()。 It's also fragile with things like simultaneous style changes on the elements.它也很脆弱,比如元素的同时风格变化。 The script below is working for me on Chrome for android 58 and Safari mobile 602.1.下面的脚本在 Chrome for android 58 和 Safari mobile 602.1 上对我有用。

var target = document.getElementsByTagName("input")[0];

if (event.target != target) {
    target.focus();
    target.click();
}

Vanilla JS solution:香草JS解决方案:

let button = document.getElementById("b");
let input = document.getElementById("i");

// Keyboard opens when focusing the input from a click listener
button.addEventListener("click", () => {
  input.focus();
});

// Input field gets focus but keyboard doesn't open.
setTimeout(() => {
  input.focus();
}, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM