设置哈希时无法聚焦输入
Unable to focus input when hash is set
我以前从未注意到这一点,但如果设置了指向现有元素的散列,似乎无法将输入字段集中在加载上。
这是为什么?
看看这个非常基本的例子:
<!doctype html>
<html>
<head>
<meta charset="utf8">
<title>Focus test</title>
</head>
<body>
<div id="bar">
<input name="foo">
</div>
<script>
console.log(document.activeElement);
document.getElementsByTagName('input')[0].focus();
console.log(document.activeElement);
</script>
</body>
</html>
如果您在 Chrome 中加载该页面,输入将被聚焦。如果您将散列设置为#bar 并重新加载页面,输入将不会 获得焦点。如果您将散列设置为#non-existing-element,输入将再次聚焦。
activeElement
表示 body
和后来的 input
不管是否设置了哈希值都不够奇怪。
考虑这个用例有 4 个场景:
- Page is
loaded
/refreshed
when there is no hash in the URL
在这种情况下,Element.focus()
工作正常。
- Hash in the URL is
appended
but page is not reloaded
/refreshed
在这种情况下,HashChangeEvent
可用于设置 focus
over 元素。
- Page is
loaded
/refreshed
when there is hash in the URL
在这种情况下,Element.focus()
工作正常 if 在 setTimeout
的 callback
中调用。即使 setTimeout(callback,0)
也行!
- Page is
loaded
/refreshed
when there is hash in the URL but target
does not exist in the Page
在这种情况下,Element.focus()
工作正常
最终想法:
要在 任何 场景中使用 focus
ever 元素,请在 window.onload
回调中使用 setTimeout
和 delay
共 0
window.onload = function () {
setTimeout(function () {
document.getElementsByTagName('input')[0].focus();
console.log(document.activeElement);
}, 0);
};
我以前从未注意到这一点,但如果设置了指向现有元素的散列,似乎无法将输入字段集中在加载上。
这是为什么?
看看这个非常基本的例子:
<!doctype html>
<html>
<head>
<meta charset="utf8">
<title>Focus test</title>
</head>
<body>
<div id="bar">
<input name="foo">
</div>
<script>
console.log(document.activeElement);
document.getElementsByTagName('input')[0].focus();
console.log(document.activeElement);
</script>
</body>
</html>
如果您在 Chrome 中加载该页面,输入将被聚焦。如果您将散列设置为#bar 并重新加载页面,输入将不会 获得焦点。如果您将散列设置为#non-existing-element,输入将再次聚焦。
activeElement
表示 body
和后来的 input
不管是否设置了哈希值都不够奇怪。
考虑这个用例有 4 个场景:
- Page is
loaded
/refreshed
when there is no hash in the URL
在这种情况下,Element.focus()
工作正常。
- Hash in the URL is
appended
but page is notreloaded
/refreshed
在这种情况下,HashChangeEvent
可用于设置 focus
over 元素。
- Page is
loaded
/refreshed
when there is hash in the URL
在这种情况下,Element.focus()
工作正常 if 在 setTimeout
的 callback
中调用。即使 setTimeout(callback,0)
也行!
- Page is
loaded
/refreshed
when there is hash in the URL buttarget
does not exist in the Page
在这种情况下,Element.focus()
工作正常
最终想法:
要在 任何 场景中使用 focus
ever 元素,请在 window.onload
回调中使用 setTimeout
和 delay
共 0
window.onload = function () {
setTimeout(function () {
document.getElementsByTagName('input')[0].focus();
console.log(document.activeElement);
}, 0);
};