我以前从未注意到这一点,但如果设置了指向现有元素的散列,则似乎不可能将输入字段集中在加载上。
这是为什么?
看看这个非常基本的例子:
<!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
超过元素。
- Page is
loaded
/refreshed
when there is hash in the URL
在本例中,Element.focus()
如果在callback
中调用则工作正常的setTimeout
。甚至是setTimeout(callback,0)
会起作用的!
- Page is
loaded
/refreshed
when there is hash in the URL buttarget
does not exist in the Page
在本例中,Element.focus()
工作正常
最终想法:
拥有focus
任何场景中的任何元素,使用setTimeout
在 window.onload
回调 delay
0
window.onload = function () {
setTimeout(function () {
document.getElementsByTagName('input')[0].focus();
console.log(document.activeElement);
}, 0);
};
关于javascript - 设置哈希后无法聚焦输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37566555/