首页 > 解决方案 > 使用 JavaScript 在移动网站中自动对焦地址栏

问题描述

是否可以使用 JavaScript 自动聚焦移动网站中的地址栏?(背景:我想在 Android 的 Chrome 浏览器上打开一个我的网站,并让地址栏专注于能够输入它)

我找到了这个代码示例,但它仅适用于网站中的输入字段:

Homepage: <input type="url" id="myURL" value="http://www.google.com">

<p>Click the buttons below to give focus and/or remove focus from the URL field.</p>

<button type="button" onclick="getFocus()">Get focus</button>
<button type="button" onclick="loseFocus()">Lose focus</button>

<p><strong>Note:</strong> elements with type="url" are not supported in IE 9 (and earlier), or Safari.</p>

<script>
function getFocus() {
  document.getElementById("myURL").focus();
}

function loseFocus() {
  document.getElementById("myURL").blur();
}
</script>

标签: javascriptgoogle-chromemobilefocus

解决方案


您可以通过 js 或其他首选编程语言将以下快捷方式发送到浏览器以关注地址栏:

Ctrl+l

推荐阅读