【问题标题】:How do I autofocus a text form field on page-load but hide the soft keyboard on mobile?如何在页面加载时自动聚焦文本表单字段但在移动设备上隐藏软键盘?
【发布时间】:2018-04-25 21:44:09
【问题描述】:

我想将 HTML 表单中的第一个字段集中在页面加载上,我目前正在使用 <input autofocus='autofocus' /> 执行此操作。

当我在移动设备上查看页面时,软键盘覆盖了提交按钮,这与我所关注的设计不相符。在用户再次点击该字段之前,如何让这个键盘保持隐藏状态?


我希望该字段专注于页面加载,以便桌面用户可以立即开始在该字段中输入内容。移动用户只需点击该字段一次即可调出软键盘。

我们没有使用任何类型的用户代理嗅探,也没有使用视口宽度来确定哪些浏览器将具有软键盘。

这是我想要做的一个例子。在移动设备上,顶部字段已聚焦,但在移动设备上不显示键盘:https://accounts.ft.com/login

【问题讨论】:

  • @31piy 不。不同的问题。
  • 金融时报只是在input element上做autofocus
  • @AjAX。你知道他们是如何阻止软键盘显示的吗?这就是我想要理解的。谢谢。
  • <input autofocus /> 是否仍会弹出键盘。我已经 - 没有 - 测试过?
  • @AjAX。是的,不幸的是。 ://

标签: javascript html forms


【解决方案1】:

这可以通过将输入字段设置为readonly,然后将超时设置为blur,然后在其上重新设置focus,以及删除readonly 属性来实现。

el = document.getElementById('myInput');
hideKeyboard(el);

function hideKeyboard(el) {
  var att = document.createAttribute("readonly");
  el.setAttributeNode(att); // Force keyboard to hide on input field.
  setTimeout(function() {
    el.blur(); //close the keyboard
    el.focus(); //focus on the input
    // Remove readonly attribute after keyboard is hidden.
    el.removeAttribute('readonly');
  }, 100);
}
<input id='myInput' autofocus />

【讨论】:

  • 谢谢你。但是以后字段自动对焦时不会弹出软键盘吗?
  • 是的,它会在正常输入字段中弹出。但不在 readonly 输入字段上。
猜你喜欢
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 2021-04-03
相关资源
最近更新 更多