如何 select 页面加载时 Chrome/Firefox 中的所有输入文本与自动对焦相结合

How to select all text of input at page load in Chrome/Firefox in combination with autofocus

我的问题是:我怎样才能让 Chrome/OperaFirefox 相信特定的输入是焦点 when/after 页面已加载(通过使用自动对焦)并且其文本默认为 selected。

最接近我的用例的答案是关于如何 select 当元素通过单击获得焦点时输入的文本。

我的问题最合适的答案(恕我直言)是:

// file: scripts.js

function onFocusSelectAll(sender) {
  // setTimeout(function () { ... }, 0) is required for edge and safari
  setTimeout(function() {
    sender.select();
  }, 0);
}
<input id="searchInput" type="text" onfocus="onFocusSelectAll(this);">

取自 this SO answer

但这只是事实的一半。尽管这在许多浏览器(edge、IE、Safari)中都有效,但在 Chrome/OperaFirefox

经过一番尝试,我发现我的解决方案实际上是正确的...

// file: scripts.js

function onFocusSelectAll(sender) {
  // setTimeout(function () { ... }, 0) is required for edge and safari
  setTimeout(function() {
    sender.select();
  }, 0);
}

...但是浏览器在不同的时间执行初始焦点事件。

Chrome/OperaFirefoxbefore执行自动对焦触发的对焦事件同步添加到页面末尾时加载外部脚本。

因此,请确保您的相关脚本加载超出其使用范围,或者您使用 inpage/inline 脚本用于该特定目的。

编辑: 另一种方法是自己处理自动对焦,根本不使用这个 属性。

(function setInitialFocus() {
  elem = document.getElementById("searchInput");
  elem.select();
})();
<input id="searchInput" type="text" onfocus="onFocusSelectAll(this);">