javascript 如何通过javascript或jquery将输入字段聚焦在Android浏览器上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8858094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to focus an input field on Android browser through javascript or jquery
提问by Ionut Bilica
I've tried $('#field').focus()
, and any other method found on the internet. Nothing worked. I have a simple html that reproduces the problem.
我已经尝试过$('#field').focus()
,以及在互联网上找到的任何其他方法。没有任何效果。我有一个简单的 html 来重现这个问题。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#field').focus();
});
</script>
</head>
<body>
<input type="text" id="field" name="field"/>
</body>
</html>
Please help!
请帮忙!
采纳答案by woobione
Actually, the general javascript function "focus" is deactivated in the android browser. Hence, the jQuery focus function is deactivated since it's using the above.
实际上,android 浏览器中禁用了通用的 javascript 功能“焦点”。因此,jQuery 焦点功能被停用,因为它使用了上述内容。
回答by user1207504
if you bind it to another click event it will work. This works for me:
如果您将其绑定到另一个点击事件,它将起作用。这对我有用:
$(document).ready(function()
{
$('#field').click(function(e){ $(this).focus(); });
$('body').click(function(e)
{
$('#field').trigger('click');
})
})
Will pop up the software keyboard. trigger() will trigger any event you give it. In this case the default behaviour of clicking on the field == tap == focus == win! Note: this call is bound to another click event happening.
会弹出软键盘。trigger() 将触发您提供的任何事件。在这种情况下,单击字段的默认行为 == 点击 == 焦点 == 获胜!注意:此调用绑定到另一个点击事件发生。
回答by bbsimonbb
click()
or focus()
alone is not enough. You need to focus()
then click()
. Beware of endless loops if your script is triggered by an onclick() on a containing element. The script below is working for me on Chrome for android 58 and Safari mobile 602.1. Soft keyboard popping nicely.
click()
或者focus()
光靠是不够的。你需要focus()
然后click()
。如果您的脚本由包含元素上的 onclick() 触发,请注意无限循环。下面的脚本在 Chrome for android 58 和 Safari mobile 602.1 上对我有用。软键盘弹得很好。
var target = document.getElementsByTagName("input")[0];
if (event.target != target) {
target.focus();
target.click();
}