【问题标题】:How can you autofocus on a form field in iPhone Safari?如何在 iPhone Safari 中自动聚焦于表单域?
【发布时间】:2011-08-11 22:08:31
【问题描述】:

我正在尝试让特定表单字段在 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>

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

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

感谢您的帮助!

【问题讨论】:

    标签: javascript iphone html focus mobile-safari


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      尝试给输入元素一个类型

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

      对于后备,您可以使用

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

      【讨论】:

      • 感谢 Husar,我已经相应地更新了代码(在上面的 URL 中),但不幸的是它仍然无法在 iPhone 4 上运行 =/
      • 不知道为什么,它应该可以工作,查看这篇文章以获得更多选项 => diveintohtml5.org/forms.html 你会在自动对焦字段下找到你需要的东西
      • @Husar 它在移动 safari 中不受支持 -- wufoo.com/html5/attributes/02-autofocus.html
      【解决方案3】:

      试试 setTimeout() 中的 .focus()。

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

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

      【讨论】:

      • 这行不通,尤其是当您使用timeout 时。在某些情况下可以工作,但前提是您不使用超时。
      猜你喜欢
      • 2023-04-09
      • 2018-04-23
      • 1970-01-01
      • 2016-01-02
      • 2023-03-04
      • 2022-11-25
      • 2021-04-15
      • 2014-01-01
      • 1970-01-01
      相关资源
      最近更新 更多