Javascript 如何在 iPhone Safari 中自动聚焦表单域?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5771785/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:46:47  来源:igfitidea点击:

How can you autofocus on a form field in iPhone Safari?

javascriptiphonehtmlfocusmobile-safari

提问by pixelphantom

I'm trying to have a particular form field get focus automatically in a Safari browser on iPhone. I thought this would be pretty straight-forward, but I'm not managing to get this working. So, is this actually not possible or am I missing something super-obvious (which I suspect)? Here is the code I'm using:

我正在尝试让特定的表单字段在 iPhone 上的 Safari 浏览器中自动获得焦点。我认为这会非常简单,但我无法使其正常工作。那么,这实际上是不可能的,还是我错过了一些非常明显的东西(我怀疑)?这是我正在使用的代码:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
   function formfocus() {
      document.getElementById('element').focus();
   }
   window.onload = formfocus;
</script>
</head>
<body>

<form>
<input/>
<input id="element" autofocus/>
<input/>
</form>

</body>
</html>

You can see I'm trying to get the focus twice, once via js and once via the HTML "aufofocus" attribute on the input field. Neither does the trick. This does work on desktop browsers, but when I open the page on my iPhone 4, no dice, that is, I have to set focus manually by clicking on one of the form fields.

您可以看到我试图获得焦点两次,一次通过 js,一次通过输入字段上的 HTML“aufofocus”属性。诀窍也没有。这确实适用于桌面浏览器,但是当我在 iPhone 4 上打开页面时,没有骰子,也就是说,我必须通过单击表单字段之一来手动设置焦点。

Ultimately what I'd like is to open the website on the mobile browser and have focus on a form field, including the keyboard opened up to start typing.

最终我想要的是在移动浏览器上打开网站并专注于表单字段,包括打开键盘以开始输入。

Thanks for any help!

谢谢你的帮助!

回答by Veera

According to this page, autofocus is not supported in iphone/ipad for usability reasons.

根据此页面,出于可用性原因,iphone/ipad 不支持自动对焦。

回答by Maverick

Try to give the input element a type

尝试给输入元素一个类型

<input type="email" id="element" autofocus/>

and for fallback you can use

对于回退,您可以使用

<script type="text/javascript">
    if (!("autofocus" in document.createElement("input"))) {
      document.getElementById("element").focus();
    }
</script>

回答by Leopathu

Try the .focus() inside of setTimeout().

试试 setTimeout() 里面的 .focus()。

setTimeout(function() {
jQuery('#element').focus();
}, 500);

I hope, it would be working on all.

我希望,它对所有人都有效。