【问题标题】:How to select all text of input at page load in Chrome/Firefox in combination with autofocus如何结合自动对焦在 Chrome/Firefox 中的页面加载时选择所有输入文本
【发布时间】:2016-12-19 10:27:20
【问题描述】:
我的问题是:我如何才能说服 Chrome/Opera 和 Firefox 在页面加载时/之后(通过使用自动对焦)关注特定输入b>而且默认选择其文本。
与我的用例最接近的答案是关于当元素通过单击获得焦点时如何选择输入的文本。
对我的问题最合适的答案(恕我直言)是:
// 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/Opera 或 Firefox
中不会选择文本
【问题讨论】:
标签:
javascript
html
google-chrome
firefox
opera
【解决方案1】:
玩了一圈后发现我的解决方案其实是正确的……
// file: scripts.js
function onFocusSelectAll(sender) {
// setTimeout(function () { ... }, 0) is required for edge and safari
setTimeout(function() {
sender.select();
}, 0);
}
...但是浏览器在不同时间执行初始焦点事件。
Chrome/Opera 和 Firefox 执行由 autofocus 触发的焦点事件 before 添加到页面末尾时加载外部脚本同步。
因此,请确保您的相关脚本在其使用量之上加载,或者您使用 inpage/inline 脚本来实现特定目的。
编辑:
另一种方法是自己处理自动对焦而不使用此属性。
(function setInitialFocus() {
elem = document.getElementById("searchInput");
elem.select();
})();
<input id="searchInput" type="text" onfocus="onFocusSelectAll(this);">